apoc 0.9.1

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

use std::collections::BTreeMap;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Version of the public apoc data contract.
pub const SCHEMA_VERSION: u32 = 8;

/// Default interval for opt-in execution telemetry.
pub const DEFAULT_TELEMETRY_INTERVAL_MS: u64 = 250;

/// Default maximum retained raw telemetry bytes.
pub const DEFAULT_TELEMETRY_MAX_BYTES: u64 = 64 * 1024 * 1024;

/// One exact command within a composed execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CommandUnit {
    /// Stable identifier unique within the parent execution.
    pub id: String,
    /// Executable followed by its exact arguments.
    pub argv: Vec<String>,
    /// Working directory, inheriting the parent workspace when omitted.
    #[serde(default)]
    pub cwd: Option<String>,
    /// Literal environment values layered over the parent environment.
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// Secret environment values layered over the parent secrets.
    #[serde(default)]
    pub secrets: BTreeMap<String, SecretRef>,
    /// Whether apoc must invoke `/bin/zsh -lc` explicitly.
    #[serde(default)]
    pub shell: bool,
    /// Command-specific wall-clock deadline in milliseconds.
    #[serde(default)]
    pub timeout_ms: Option<u64>,
    /// Result the caller asserts this one command must produce.
    ///
    /// Every declared command carries its own assertion, because a batch has no single
    /// output to assert against. An unmet expectation fails the command and its parent.
    #[serde(default)]
    pub expect: Option<PollCondition>,
}

/// How commands in one composed execution exchange control and data.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CommandTopology {
    /// Independent commands scheduled with bounded concurrency.
    Parallel {
        /// Maximum number of commands running at once.
        max_parallel: u32,
        /// Stop launching queued commands after the first failure.
        #[serde(default)]
        fail_fast: bool,
    },
    /// Ordered commands connected through native operating-system pipes.
    Pipeline {
        /// Fail when any stage exits unsuccessfully instead of only the final stage.
        #[serde(default = "pipefail_default")]
        pipefail: bool,
    },
}

fn pipefail_default() -> bool {
    true
}

/// Stable identity for one operating-system process.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub struct ProcessIdentity {
    /// Identifier for the current host boot.
    #[serde(default)]
    pub boot_id: String,
    /// Operating-system process identifier.
    pub pid: u32,
    /// Parent process identifier, when available.
    pub ppid: Option<u32>,
    /// Process group identifier on Unix.
    pub pgid: Option<u32>,
    /// Absolute Unix start timestamp in seconds.
    pub started_at: u64,
    /// Absolute Unix start timestamp in nanoseconds at the best host resolution.
    #[serde(default)]
    pub started_at_ns: u64,
    /// Executable name.
    pub name: String,
    /// Executable path, when available.
    pub executable: Option<String>,
}

/// Program executed by an apoc execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ExecutionProgram {
    /// Exact executable and argument vector.
    Command {
        /// Executable followed by its arguments.
        argv: Vec<String>,
        /// Whether apoc must invoke `/bin/zsh -lc` explicitly.
        shell: bool,
    },
    /// Exact commands composed as a bounded batch or linear native pipeline.
    Commands {
        /// Commands in declaration order.
        commands: Vec<CommandUnit>,
        /// Scheduling and data-flow topology.
        topology: CommandTopology,
    },
    /// JavaScript evaluated by Code Mode.
    Javascript {
        /// JavaScript source.
        source: String,
        /// Structured input exposed to the program.
        #[serde(default)]
        input: serde_json::Value,
    },
    /// Repeated target evaluation governed by a durable polling policy.
    Poll {
        /// Exact command or typed apoc operation evaluated by each iteration.
        target: PollTarget,
        /// Delay or tick policy between unmatched iterations.
        schedule: PollSchedule,
        /// Optional outcome condition. Bound-only polls collect samples.
        #[serde(default)]
        condition: Option<PollCondition>,
        /// Maximum number of iterations, including the first.
        #[serde(default)]
        max_iterations: Option<u64>,
        /// Hard parent deadline measured from durable acceptance.
        #[serde(default)]
        duration_ms: Option<u64>,
        /// Optional deadline applied independently to each iteration.
        #[serde(default)]
        iteration_timeout_ms: Option<u64>,
    },
}

/// Work evaluated by one poll iteration.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PollTarget {
    /// Exact executable and argument vector.
    Command {
        /// Executable followed by its exact arguments.
        argv: Vec<String>,
        /// Whether apoc must invoke `/bin/zsh -lc` explicitly.
        #[serde(default)]
        shell: bool,
    },
    /// One schema-validated operation from apoc's shared typed command graph.
    ApocCall {
        /// Canonical dotted or Code Mode underscore method name.
        method: String,
        /// Static structured arguments supplied to every iteration.
        #[serde(default)]
        arguments: serde_json::Value,
    },
}

/// Timing policy between poll iterations.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PollSchedule {
    /// Wait a fixed delay after each unmatched observation.
    FixedDelay {
        /// Delay in milliseconds.
        interval_ms: u64,
    },
    /// Increase the post-observation delay until a fixed cap.
    Backoff {
        /// Initial delay in milliseconds.
        initial_interval_ms: u64,
        /// Exponential multiplier, at least 1.0.
        multiplier: f64,
        /// Maximum delay in milliseconds.
        max_interval_ms: u64,
    },
    /// Run on fixed ticks from acceptance and skip missed ticks.
    FixedRate {
        /// Tick interval in milliseconds.
        interval_ms: u64,
    },
}

impl Default for PollSchedule {
    fn default() -> Self {
        Self::FixedDelay { interval_ms: 1000 }
    }
}

/// Condition that completes a poll when one observation matches.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PollCondition {
    /// Match a command exit code.
    ExitCode {
        /// Accepted process exit codes.
        codes: Vec<i32>,
    },
    /// Match the redacted standard-output tail using Rust regex syntax.
    StdoutRegex {
        /// Regular expression.
        pattern: String,
    },
    /// Match the redacted standard-error tail using Rust regex syntax.
    StderrRegex {
        /// Regular expression.
        pattern: String,
    },
    /// Compare a value selected through a JSON Pointer.
    JsonEquals {
        /// RFC 6901 JSON Pointer into parsed command stdout or typed result JSON.
        pointer: String,
        /// Exact JSON value required at the pointer.
        value: serde_json::Value,
    },
    /// Evaluate one pure JavaScript boolean expression over `observation`.
    Javascript {
        /// Side-effect-free expression evaluated in bounded QuickJS.
        expression: String,
    },
}

/// Durable lifecycle phase for one poll iteration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PollIterationStatus {
    /// Iteration number was durably reserved before dispatch.
    Accepted,
    /// The target is being evaluated.
    Running,
    /// A complete observation was durably recorded.
    Observed,
    /// The parent deadline or caller canceled the active iteration.
    Canceled,
    /// The target could not be launched or safely observed.
    Failed,
}

/// Complete durable evidence for one poll iteration.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PollIteration {
    /// Stable iteration identifier.
    pub id: String,
    /// Owning poll execution identifier.
    pub poll_id: String,
    /// One-based iteration number.
    pub number: u64,
    /// Current durable iteration status.
    pub status: PollIterationStatus,
    /// Start timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Terminal timestamp, when available.
    pub completed_at: Option<u64>,
    /// Child execution identifier for command targets.
    pub execution_id: Option<String>,
    /// Retained content-addressed payload for oversized typed results.
    pub payload_id: Option<String>,
    /// Bounded normalized observation used by the condition.
    pub observation: Option<serde_json::Value>,
    /// Whether this iteration satisfied the requested condition.
    pub matched: bool,
    /// Whether the persisted observation has been evaluated against the condition.
    #[serde(default)]
    pub evaluated: bool,
    /// Stable failure code, when the iteration itself failed.
    pub error_code: Option<String>,
    /// Human-readable failure detail.
    pub error: Option<String>,
}

/// Compact poll iteration identity returned by bounded pages.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PollIterationSummary {
    pub id: String,
    pub poll_id: String,
    pub number: u64,
    pub status: PollIterationStatus,
    pub started_at: u64,
    pub completed_at: Option<u64>,
    pub execution_id: Option<String>,
    pub payload_id: Option<String>,
    pub matched: bool,
    pub error_code: Option<String>,
}

/// Bounded newest-first page of poll iterations.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PollIterationPage {
    pub iterations: Vec<PollIterationSummary>,
    pub next_cursor: Option<String>,
}

/// Lifetime owner for an execution or resource lease.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum LeaseOwnerKind {
    /// A parent execution owns the lease.
    Execution,
    /// An agent session owns the lease.
    Session,
    /// The lease survives callers until explicit release or expiry.
    Persistent,
}

/// Finite retry behavior for an execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RetryPolicy {
    /// Maximum total attempts, including the first attempt.
    pub max_attempts: u32,
    /// Initial delay before retrying.
    pub backoff_ms: u64,
    /// Maximum delay between attempts.
    pub max_backoff_ms: u64,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            max_attempts: 1,
            backoff_ms: 500,
            max_backoff_ms: 30_000,
        }
    }
}

/// Enforceable limits for one execution.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionBudget {
    /// Maximum wall-clock lifetime in milliseconds.
    pub wall_time_ms: Option<u64>,
    /// Maximum combined resident memory for the execution family, in bytes.
    #[serde(default)]
    pub memory_bytes: Option<u64>,
    /// Maximum combined CPU use, where 100 percent equals one logical CPU.
    #[serde(default)]
    pub cpu_percent: Option<f32>,
    /// Maximum accumulated CPU time for the execution family, in milliseconds.
    #[serde(default)]
    pub cpu_time_ms: Option<u64>,
    /// Maximum child process count.
    pub child_processes: Option<u32>,
    /// Maximum retained output and artifact bytes.
    pub artifact_bytes: Option<u64>,
    /// Maximum time without progress before apoc reports a stall.
    pub progress_timeout_ms: Option<u64>,
    /// Whether a reported stall must cancel the execution.
    #[serde(default)]
    pub cancel_on_stall: bool,
}

/// Opt-in resource telemetry policy for one execution family.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum TelemetryPolicy {
    /// Do not start a sampler or retain telemetry.
    #[default]
    Off,
    /// Sample the execution family at a bounded interval.
    Sample {
        /// Milliseconds between samples.
        interval_ms: u64,
        /// Maximum retained raw telemetry bytes.
        max_bytes: u64,
    },
}

/// Lifecycle state for one durable execution telemetry capture.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TelemetryCaptureStatus {
    /// Sampling is active.
    Active,
    /// The caller stopped sampling.
    Stopped,
    /// The execution family became terminal and sampling finished.
    Completed,
    /// Sampling stopped because telemetry collection failed.
    Degraded,
}

/// Durable metadata for one execution-family telemetry capture.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TelemetryCapture {
    /// Public schema version used by this record.
    pub schema_version: u32,
    /// Stable capture identifier.
    pub id: String,
    /// Root execution whose recursively owned family is sampled.
    pub execution_id: String,
    /// Milliseconds between samples.
    pub interval_ms: u64,
    /// Maximum retained raw sample bytes.
    pub max_bytes: u64,
    /// Capture lifecycle state.
    pub status: TelemetryCaptureStatus,
    /// Capture start in Unix milliseconds.
    pub started_at: u64,
    /// Capture stop in Unix milliseconds, when terminal.
    pub stopped_at: Option<u64>,
    /// Next stable raw-sample sequence.
    pub next_sequence: u64,
    /// Number of retained samples.
    pub sample_count: u64,
    /// Bytes retained for raw samples.
    pub retained_bytes: u64,
    /// Samples removed from the front of the capture to enforce max_bytes.
    pub dropped_samples: u64,
    /// Most recent collection fault. It never changes the execution verdict.
    pub error: Option<String>,
}

/// One process measurement retained inside an execution telemetry sample.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TelemetryProcessSample {
    /// Stable boot, PID, and nanosecond start-time identity.
    pub identity: ProcessIdentity,
    /// CPU use as a percentage of one logical CPU.
    pub cpu_percent: f32,
    /// Accumulated CPU time in milliseconds.
    pub cpu_time_ms: u64,
    /// Resident memory in bytes.
    pub memory_bytes: u64,
    /// Virtual memory in bytes.
    pub virtual_memory_bytes: u64,
    /// Total bytes read from storage.
    pub disk_read_bytes: u64,
    /// Total bytes written to storage.
    pub disk_written_bytes: u64,
}

/// One timestamped measurement of an execution and every recursive descendant.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TelemetrySample {
    /// Stable sequence within the capture.
    pub sequence: u64,
    /// Observation time in Unix milliseconds.
    pub sampled_at: u64,
    /// Elapsed time since capture start.
    pub wall_time_ms: u64,
    /// Number of live processes in the execution family.
    pub process_count: u64,
    /// Sum of current per-process CPU percentages.
    pub cpu_percent: f32,
    /// Sum of accumulated process CPU time in milliseconds.
    pub cpu_time_ms: u64,
    /// Sum of resident memory in bytes.
    pub memory_bytes: u64,
    /// Sum of virtual memory in bytes.
    pub virtual_memory_bytes: u64,
    /// Sum of total bytes read from storage.
    pub disk_read_bytes: u64,
    /// Sum of total bytes written to storage.
    pub disk_written_bytes: u64,
    /// Per-process measurements without command lines or environment data.
    pub processes: Vec<TelemetryProcessSample>,
}

/// Compact telemetry answer returned when no addressed raw read was requested.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TelemetrySummary {
    /// Durable capture metadata.
    pub capture: TelemetryCapture,
    /// Newest retained measurement, when one exists.
    pub latest: Option<TelemetrySummarySample>,
    /// Peak CPU percentage across retained measurements.
    pub peak_cpu_percent: Option<f32>,
    /// Peak resident memory across retained measurements.
    pub peak_memory_bytes: Option<u64>,
    /// Peak live process count across retained measurements.
    pub peak_process_count: Option<u64>,
}

/// Aggregate-only sample used by the compact telemetry summary.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TelemetrySummarySample {
    /// Stable sequence within the capture.
    pub sequence: u64,
    /// Observation time in Unix milliseconds.
    pub sampled_at: u64,
    /// Elapsed time since capture start.
    pub wall_time_ms: u64,
    /// Number of live processes in the execution family.
    pub process_count: u64,
    /// Sum of current per-process CPU percentages.
    pub cpu_percent: f32,
    /// Sum of accumulated process CPU time in milliseconds.
    pub cpu_time_ms: u64,
    /// Sum of resident memory in bytes.
    pub memory_bytes: u64,
    /// Sum of virtual memory in bytes.
    pub virtual_memory_bytes: u64,
    /// Sum of total bytes read from storage.
    pub disk_read_bytes: u64,
    /// Sum of total bytes written to storage.
    pub disk_written_bytes: u64,
}

/// One numbered raw NDJSON telemetry line.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TelemetryLine {
    /// Stable sample sequence.
    pub sequence: u64,
    /// Serialized sample JSON.
    pub text: String,
}

/// Bounded addressed read over retained raw telemetry.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TelemetrySlice {
    /// Stable capture identifier.
    pub capture_id: String,
    /// Number of retained raw lines considered.
    pub total_lines: u64,
    /// Total matching lines before the response limit.
    pub total_matches: u64,
    /// Numbered lines returned to the caller.
    pub lines: Vec<TelemetryLine>,
    /// Whether matching lines were withheld by the response limit.
    pub truncated: bool,
}

/// Repository and worktree context captured for an execution.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct WorkspaceContext {
    /// Current working directory.
    pub cwd: Option<String>,
    /// Repository root, when detected.
    pub repository: Option<String>,
    /// Worktree root, when detected.
    pub worktree: Option<String>,
    /// Current commit, when detected.
    pub commit: Option<String>,
    /// Current branch, when detected.
    pub branch: Option<String>,
    /// Digest of the dirty worktree state without copied file contents.
    pub dirty_digest: Option<String>,
}

/// Public definition of one durable agent execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionSpec {
    /// Public contract version.
    pub schema_version: u32,
    /// Stable caller key that prevents duplicate execution launches.
    #[serde(default)]
    pub idempotency_key: Option<String>,
    /// Human-readable name.
    pub name: String,
    /// Agent-supplied reason for the execution.
    pub purpose: Option<String>,
    /// Searchable labels.
    #[serde(default)]
    pub labels: BTreeMap<String, String>,
    /// Program to execute.
    pub program: ExecutionProgram,
    /// Runtime responsible for launching the program.
    #[serde(default)]
    pub backend: ExecutionBackendSpec,
    /// Working directory and repository context.
    #[serde(default)]
    pub workspace: WorkspaceContext,
    /// Explicit environment values. Literal values are recordable.
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// Secret references resolved only while launching the program.
    #[serde(default)]
    pub secrets: BTreeMap<String, SecretRef>,
    /// One exclusive durable profile selected before execution acceptance.
    #[serde(default)]
    pub profile_selection: Option<ProfileSelection>,
    /// Process I/O mode for command programs.
    pub io: IoMode,
    /// Lease owner kind.
    pub owner_kind: LeaseOwnerKind,
    /// Owning execution or session identifier, when applicable.
    pub owner_id: Option<String>,
    /// Optional absolute lease expiry in Unix milliseconds.
    pub expires_at: Option<u64>,
    /// Finite retry behavior.
    #[serde(default)]
    pub retry: RetryPolicy,
    /// Resource budgets.
    #[serde(default)]
    pub budget: ExecutionBudget,
    /// Resource telemetry captured for this execution family.
    #[serde(default)]
    pub telemetry: TelemetryPolicy,
    /// Result the caller asserts this execution must produce.
    ///
    /// A poll evaluates the same predicate repeatedly; a command evaluates it once, when the
    /// execution reaches its terminal state. An unmet expectation is a `failed` verdict.
    #[serde(default)]
    pub expect: Option<PollCondition>,
}

/// Runtime responsible for launching one execution program.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ExecutionBackendSpec {
    /// Launch directly through apoc's native managed-run engine.
    #[default]
    Native,
    /// Launch through apoc's built-in isolated macOS virtual machine backend.
    Isolated {
        /// Typed isolation contract; transport details remain internal to apoc.
        isolation: IsolatedExecutionSpec,
    },
    /// Launch through one immutable generation of a registered provider.
    Provider {
        /// Registered provider name.
        name: String,
        /// Provider configuration and capability generation.
        generation: String,
        /// Provider-specific execution options.
        #[serde(default)]
        options: serde_json::Value,
    },
}

/// One command's built-in isolated execution contract.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct IsolatedExecutionSpec {
    /// `local`, an absolute VM bundle path, or a canonical `sha256:<digest>` reference.
    pub image: String,
    /// Whether the normalized host workspace is mounted at `/workspace`.
    #[serde(default)]
    pub workspace: IsolatedWorkspaceMode,
    /// Optional absolute working directory inside the guest.
    #[serde(default)]
    pub guest_cwd: Option<String>,
    /// Guest memory limit in mebibytes.
    #[serde(default)]
    pub memory_mb: Option<u64>,
    /// Guest virtual CPU count.
    #[serde(default)]
    pub cpu_count: Option<u32>,
    /// Guest process-count limit.
    #[serde(default)]
    pub pids_max: Option<u32>,
    /// Guest network policy.
    #[serde(default)]
    pub network: IsolatedNetworkPolicy,
    /// Files imported as content-addressed artifacts after the command.
    #[serde(default)]
    pub exports: Vec<ExecutionExportSpec>,
}

/// Host workspace projection into an isolated guest.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum IsolatedWorkspaceMode {
    /// Do not expose a host workspace to the guest.
    None,
    /// Mount the normalized host workspace read-write at `/workspace`.
    #[default]
    ReadWrite,
}

/// Network access available to an isolated guest.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum IsolatedNetworkPolicy {
    /// Do not attach a network device.
    #[default]
    None,
    /// Attach the Virtualization framework NAT network device.
    Nat,
}

/// One file exported from an isolated guest after execution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionExportSpec {
    /// Absolute guest path to export.
    pub source: String,
    /// Stable caller-facing artifact name.
    pub destination: String,
    /// Terminal condition under which the export is collected.
    #[serde(default)]
    pub when: ExecutionExportWhen,
}

/// Terminal condition that controls an isolated file export.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionExportWhen {
    /// Export only after a zero exit status.
    #[default]
    Success,
    /// Export only after a nonzero exit status.
    Failure,
    /// Export after either command outcome.
    Always,
}

/// One verified content-addressed artifact imported from an isolated guest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionArtifactRef {
    /// Stable caller-facing artifact name from the export declaration.
    pub name: String,
    /// Absolute path requested inside the guest.
    pub source: String,
    /// Apoc content-addressed artifact identifier.
    pub id: String,
    /// Raw archive byte count.
    pub bytes: u64,
    /// Guest-declared SHA-256 verified over the raw archive bytes.
    pub guest_sha256: String,
    /// Stored artifact media type.
    pub media_type: String,
}

/// Reference to a secret that apoc must not persist after resolution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SecretRef {
    /// Secret provider name.
    pub provider: String,
    /// Provider-specific reference identifier.
    pub reference: String,
    /// Optional provider version that does not contain the secret value.
    pub version: Option<String>,
}

/// Source that selected one durable profile for an operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ProfileSelectionSource {
    /// The caller named the profile explicitly.
    Explicit,
    /// A canonical workspace root selected the profile.
    Workspace,
    /// The configured per-user default selected the profile.
    UserDefault,
}

/// One immutable profile definition selected for an execution graph.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ProfileSelection {
    /// Stable profile name.
    pub name: String,
    /// Immutable digest of the selected profile definition.
    pub generation: String,
    /// Rule that selected this profile.
    pub source: ProfileSelectionSource,
    /// Canonical workspace root that matched, when selection was workspace-based.
    #[serde(default)]
    pub matched_root: Option<String>,
    /// Secret-safe environment variable names controlled by this generation.
    #[serde(default)]
    pub variables: Vec<String>,
}

/// One secret-safe value exposed by profile inspection commands.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ProfileEntry {
    /// Destination environment variable name.
    pub name: String,
    /// Stored value kind: literal or secret.
    pub kind: String,
    /// Whether the value can resolve now without returning it.
    pub resolvable: bool,
    /// Stable diagnostic code when resolution is unavailable.
    #[serde(default)]
    pub error_code: Option<String>,
}

/// Secret-safe public view of one durable profile.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ProfileView {
    /// Stable profile name.
    pub name: String,
    /// Immutable digest of the current definition.
    pub generation: String,
    /// Whether this profile is the per-user default.
    pub is_default: bool,
    /// Canonical workspace roots mapped to this profile.
    #[serde(default)]
    pub roots: Vec<String>,
    /// Secret-safe environment entries.
    #[serde(default)]
    pub entries: Vec<ProfileEntry>,
}

/// Result of resolving profile selection for one canonical workspace.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ProfileResolution {
    /// Canonical workspace used for root matching.
    #[serde(default)]
    pub cwd: Option<String>,
    /// Selected immutable profile, or none for credential-free work.
    #[serde(default)]
    pub selection: Option<ProfileSelection>,
}

/// Whether a provider consumes profile-backed values.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ProfileMode {
    /// Provider ignores profiles and preserves its static configuration.
    #[default]
    None,
    /// Provider uses profile mappings when a profile is selected.
    Optional,
    /// Provider rejects dispatch without a selected profile.
    Required,
}

/// Durable execution state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionStatus {
    /// Accepted but not yet running.
    Queued,
    /// Actively evaluating or supervising work.
    Running,
    /// No progress was observed before the configured deadline.
    Stalled,
    /// Replay or an external event may resume the execution.
    Interrupted,
    /// Completed successfully.
    Completed,
    /// Completed unsuccessfully.
    Failed,
    /// Canceled by its owner or budget.
    Canceled,
}

/// One resumable evaluation pass of an execution program.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionPass {
    /// Stable pass identifier.
    pub id: String,
    /// One-based pass number.
    pub number: u32,
    /// Pass start timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Pass completion timestamp, when terminal.
    pub completed_at: Option<u64>,
    /// Current pass status.
    pub status: ExecutionStatus,
    /// Error code, when unsuccessful.
    pub error_code: Option<String>,
    /// Human-readable failure detail.
    pub error: Option<String>,
}

/// One concrete process attempt owned by an execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionAttempt {
    /// Stable attempt identifier.
    pub id: String,
    /// One-based attempt number.
    pub number: u32,
    /// Exact process identities created by this attempt.
    #[serde(default)]
    pub processes: Vec<ProcessIdentity>,
    /// Attempt start timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Attempt completion timestamp, when terminal.
    pub completed_at: Option<u64>,
    /// Process exit code, when known.
    pub exit_code: Option<i32>,
    /// Stable outcome code, when unsuccessful.
    pub error_code: Option<String>,
    /// Standard-output artifact identifier, when retained.
    pub stdout_artifact: Option<String>,
    /// Standard-error artifact identifier, when retained.
    pub stderr_artifact: Option<String>,
}

/// Durable record of one agent execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Execution {
    /// Stable execution identifier.
    pub id: String,
    /// Parent execution, when this execution was composed by another.
    pub parent_id: Option<String>,
    /// Owning agent session, when applicable.
    pub session_id: Option<String>,
    /// Definition used to create the execution.
    pub spec: ExecutionSpec,
    /// Current execution status.
    pub status: ExecutionStatus,
    /// Evaluation passes in chronological order.
    #[serde(default)]
    pub passes: Vec<ExecutionPass>,
    /// Process attempts in chronological order.
    #[serde(default)]
    pub attempts: Vec<ExecutionAttempt>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last state update in Unix milliseconds.
    pub updated_at: u64,
    /// Last observed progress in Unix milliseconds.
    pub last_progress_at: u64,
    /// Structured final result or summary.
    pub result: Option<serde_json::Value>,
}

/// Durable result key recording that a declared command never launched.
pub const RESULT_SKIPPED: &str = "skipped";
/// Durable result key recording the terminal process exit code.
pub const RESULT_EXIT_CODE: &str = "exit_code";
/// Durable result key recording how a command group's declared children terminated.
pub const RESULT_COUNTS: &str = "counts";
/// Durable result key recording whether a declared expectation held.
pub const RESULT_EXPECTATION_MET: &str = "expectation_met";
/// Durable result key recording why a declared expectation could not be judged.
pub const RESULT_EXPECTATION_ERROR: &str = "expectation_error";
/// Durable result key preserving a non-object result displaced by a judgment.
pub const RESULT_DISPLACED: &str = "result";

/// Judgment the caller's declared expectation reached.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExpectationState {
    /// The caller declared no expectation, so nothing was asserted.
    NotDeclared,
    /// The declared expectation held.
    Met,
    /// The declared expectation did not hold.
    Unmet,
    /// An expectation was declared but reached no recorded judgment.
    Unevaluated,
}

impl Execution {
    /// Returns the stable terminal failure code recorded by the execution, newest first.
    pub fn recorded_error_code(&self) -> Option<&str> {
        self.attempts
            .last()
            .and_then(|attempt| attempt.error_code.as_deref())
            .or_else(|| {
                self.passes
                    .last()
                    .and_then(|pass| pass.error_code.as_deref())
            })
            .or_else(|| {
                self.result
                    .as_ref()
                    .and_then(|result| result.get("error_code"))
                    .and_then(serde_json::Value::as_str)
            })
    }

    /// Returns the result value stored under one durable key.
    fn result_key(&self, key: &str) -> Option<&serde_json::Value> {
        self.result.as_ref().and_then(|result| result.get(key))
    }

    /// Returns whether this execution was declared but never launched.
    pub fn skipped(&self) -> bool {
        self.result_key(RESULT_SKIPPED)
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false)
    }

    /// Returns the exit code this execution recorded, before any status default.
    pub fn exit_code(&self) -> Option<i32> {
        self.result_key(RESULT_EXIT_CODE)
            .and_then(serde_json::Value::as_i64)
            .and_then(|code| i32::try_from(code).ok())
            .or_else(|| self.attempts.last().and_then(|attempt| attempt.exit_code))
    }

    /// Returns whether this execution reached a verdict rather than faulting before one.
    ///
    /// A command reaches a verdict by exiting. A command group reaches one when its declared
    /// children were counted, which is the moment the group can say whether the work failed
    /// rather than whether apoc broke. An exit code alone is too narrow a proxy: it would
    /// report every failed batch as a fault.
    pub fn reached_verdict(&self) -> bool {
        self.exit_code().is_some() || self.result_key(RESULT_COUNTS).is_some()
    }

    /// Returns the judgment this execution's declared expectation reached.
    ///
    /// A declared expectation with no recorded judgment is `Unevaluated`, never `Met`. That
    /// distinction is what keeps an assertion apoc failed to evaluate from reporting `passed`.
    pub fn expectation(&self) -> ExpectationState {
        if self.spec.expect.is_none() {
            return ExpectationState::NotDeclared;
        }
        match self
            .result_key(RESULT_EXPECTATION_MET)
            .and_then(serde_json::Value::as_bool)
        {
            Some(true) => ExpectationState::Met,
            Some(false) => ExpectationState::Unmet,
            None => ExpectationState::Unevaluated,
        }
    }

    /// Records the judgment a declared expectation reached.
    ///
    /// The result is promoted to an object first, so recording can never silently do nothing
    /// and leave an unjudged assertion looking like a pass. A non-object result is preserved
    /// under `RESULT_DISPLACED` rather than discarded.
    pub fn record_expectation(&mut self, met: bool, error: Option<String>) {
        let mut result = match self.result.take() {
            Some(serde_json::Value::Object(map)) => map,
            Some(other) => {
                let mut map = serde_json::Map::new();
                map.insert(RESULT_DISPLACED.to_string(), other);
                map
            }
            None => serde_json::Map::new(),
        };
        result.insert(
            RESULT_EXPECTATION_MET.to_string(),
            serde_json::Value::Bool(met),
        );
        if let Some(error) = error {
            result.insert(
                RESULT_EXPECTATION_ERROR.to_string(),
                serde_json::Value::String(error),
            );
        }
        self.result = Some(serde_json::Value::Object(result));
    }
}

/// Current relationship between a durable execution and the host process table.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionTreeState {
    /// The execution is nonterminal but has not published a live process yet.
    Pending,
    /// At least one current process matches a captured stable launch identity.
    Active,
    /// Every owned execution is terminal and no captured process remains live.
    Terminal,
    /// Durable execution state contradicts the current stable process identities.
    Inconsistent,
}

/// One process root durably captured by an execution attempt.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionTreeRoot {
    /// Execution that owns this process root.
    pub execution_id: String,
    /// Attempt that captured this process root.
    pub attempt_id: String,
    /// Stable captured process identity.
    pub identity: ProcessIdentity,
    /// Whether that exact process lifetime is currently visible.
    pub live: bool,
}

/// Fresh process-tree observation resolved from one durable execution identity.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionTree {
    /// Execution requested by the caller.
    pub execution_id: String,
    /// Current status of the requested execution.
    pub status: ExecutionStatus,
    /// Relationship between durable state and current host processes.
    pub state: ExecutionTreeState,
    /// Observation timestamp in Unix milliseconds.
    pub observed_at: u64,
    /// Every process root captured by the execution and its recursively owned children.
    pub roots: Vec<ExecutionTreeRoot>,
    /// Fresh live roots and descendants in parent-first order.
    pub processes: Vec<ProcessInfo>,
}

/// Compact program identity returned by execution history pages.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionProgramSummary {
    /// Program kind: command, batch, pipeline, or javascript.
    pub kind: String,
    /// Bounded executable identity for command programs.
    pub executable: Option<String>,
    /// Number of arguments after the executable.
    pub argument_count: usize,
    /// Number of commands in a batch or pipeline.
    pub command_count: usize,
}

/// Compact durable execution identity returned by history pages.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionSummary {
    /// Stable execution identifier.
    pub id: String,
    /// Parent execution identifier, when composed.
    pub parent_id: Option<String>,
    /// Owning session identifier, when applicable.
    pub session_id: Option<String>,
    /// Stable caller idempotency key, when supplied.
    pub idempotency_key: Option<String>,
    /// Bounded human-readable execution name.
    pub name: String,
    /// Whether the stored name was shortened for this summary.
    pub name_truncated: bool,
    /// Current durable execution status.
    pub status: ExecutionStatus,
    /// Compact program identity.
    pub program: ExecutionProgramSummary,
    /// Bounded canonical working directory.
    pub cwd: Option<String>,
    /// Whether the stored working directory was shortened for this summary.
    pub cwd_truncated: bool,
    /// Number of process attempts recorded.
    pub attempt_count: usize,
    /// Terminal process exit code, when available.
    pub exit_code: Option<i32>,
    /// Stable terminal error code, when available.
    pub error_code: Option<String>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last state update in Unix milliseconds.
    pub updated_at: u64,
}

/// Environment variable that selects the default response verbosity.
pub const VERBOSITY_ENV: &str = "APOC_VERBOSITY";

/// Deprecated environment variable retained for one release.
pub const RESPONSE_VIEW_ENV: &str = "APOC_VIEW";

/// How much of a durable execution a response returns.
///
/// Levels follow syslog and `tracing`, and each level is a strict superset of the level
/// below it. `Error` is the default: apoc answers with a verdict and nothing else until a
/// caller asks for more, which is the `Prefer: return=minimal` posture from RFC 7240.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum Verbosity {
    /// No payload at all. The process exit status carries the result.
    Off,
    /// Durable identifier and one-word verdict.
    Error,
    /// Adds anomalies worth attention: stable error code, replay, and truncation.
    Warn,
    /// Adds routine accounting: durable status, exit code, withheld sizes, follow-up reads.
    Info,
    /// Adds bounded log tails for every outcome.
    Debug,
    /// The complete durable record, including spec, passes, attempts, and logs.
    Trace,
}

impl Verbosity {
    /// Default level applied when no caller, context, or environment selects one.
    pub const DEFAULT: Self = Self::Error;

    /// Returns the stable wire name for this level.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Error => "error",
            Self::Warn => "warn",
            Self::Info => "info",
            Self::Debug => "debug",
            Self::Trace => "trace",
        }
    }

    /// Parses one caller-supplied level name.
    pub fn parse(value: &str) -> Result<Self, String> {
        match value.trim() {
            "off" | "silent" | "none" => Ok(Self::Off),
            "error" => Ok(Self::Error),
            "warn" | "warning" => Ok(Self::Warn),
            "info" => Ok(Self::Info),
            "debug" => Ok(Self::Debug),
            "trace" => Ok(Self::Trace),
            value => Err(format!(
                "Unknown verbosity \"{value}\". Use off, error, warn, info, debug, or trace."
            )),
        }
    }

    /// Parses one deprecated `--view` name.
    ///
    /// Each name keeps the contract it had before the ladder replaced it. `outcome` asked for
    /// the collapsed verdict and still resolves to the minimal default rather than silently
    /// widening to a level its caller never requested.
    pub fn parse_view(value: &str) -> Result<Self, String> {
        match value.trim() {
            "outcome" => Ok(Self::DEFAULT),
            "full" => Ok(Self::Trace),
            value => Err(format!("Unknown view \"{value}\". Use full or outcome.")),
        }
    }

    /// Moves along the ladder that `-v` and `-q` walk.
    ///
    /// `Warn` is deliberately not a step. It is a named opt-in that reports anomalies and
    /// nothing else, so counting flags run `off → error → info → debug → trace` and a caller
    /// who wants anomaly-only responses asks for `--verbosity warn` by name.
    pub fn shift(self, steps: i32) -> Self {
        const STEPS: [Verbosity; 5] = [
            Verbosity::Off,
            Verbosity::Error,
            Verbosity::Info,
            Verbosity::Debug,
            Verbosity::Trace,
        ];
        if steps == 0 {
            return self;
        }
        // Warn walks from the error rung, so raising it once reaches info.
        let current = STEPS.iter().position(|level| *level == self).unwrap_or(1) as i32;
        let index = (current + steps).clamp(0, STEPS.len() as i32 - 1) as usize;
        STEPS[index]
    }

    /// Reads `APOC_VERBOSITY`, then the deprecated `APOC_VIEW`.
    pub fn from_env() -> Option<Result<Self, String>> {
        if let Ok(value) = std::env::var(VERBOSITY_ENV)
            && !value.trim().is_empty()
        {
            return Some(Self::parse(&value));
        }
        if let Ok(value) = std::env::var(RESPONSE_VIEW_ENV)
            && !value.trim().is_empty()
        {
            return Some(Self::parse_view(&value));
        }
        None
    }
}

/// Verdict for one durable execution, using the JUnit and TAP vocabulary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionVerdict {
    /// Ran to completion and either exited zero or met its declared expectation.
    Passed,
    /// The assertion did not hold: a nonzero exit, or a declared expectation missed.
    Failed,
    /// An apoc-level fault reached no verdict: launch failure, stall, or cancellation.
    Error,
    /// Declared but never launched.
    Skipped,
    /// Durably owned and not yet terminal.
    Pending,
}

impl ExecutionVerdict {
    /// Judges one durable execution from its own recorded state.
    ///
    /// This is the single place every surface derives a verdict, so a CLI response, a parent
    /// command group, and a later read of the same record cannot disagree.
    ///
    /// A command that ran without a declared expectation and reported a nonzero exit `Failed`.
    /// A met declared expectation `Passed` even when the process exited nonzero. One that never
    /// reached a verdict at all is an `Error`, the same distinction JUnit draws between a failing
    /// assertion and a broken harness. A declared expectation that reached no judgment is
    /// that same broken harness: silence about an assertion must never read as it holding.
    pub fn of_execution(execution: &Execution) -> Self {
        if execution.skipped() {
            return Self::Skipped;
        }
        match execution.status {
            ExecutionStatus::Completed => match (execution.expectation(), execution.exit_code()) {
                (ExpectationState::Unevaluated, _) => Self::Error,
                (ExpectationState::Unmet, _) => Self::Failed,
                (ExpectationState::Met, _) => Self::Passed,
                (ExpectationState::NotDeclared, Some(0) | None) => Self::Passed,
                (ExpectationState::NotDeclared, Some(_)) => Self::Failed,
            },
            ExecutionStatus::Failed if execution.reached_verdict() => {
                match execution.expectation() {
                    ExpectationState::Unevaluated => Self::Error,
                    ExpectationState::Met => Self::Passed,
                    ExpectationState::Unmet | ExpectationState::NotDeclared => Self::Failed,
                }
            }
            ExecutionStatus::Failed | ExecutionStatus::Canceled | ExecutionStatus::Stalled => {
                Self::Error
            }
            ExecutionStatus::Queued | ExecutionStatus::Running | ExecutionStatus::Interrupted => {
                Self::Pending
            }
        }
    }
}

/// Execution response carrying only what the requested verbosity level admits.
///
/// Every field below `Verbosity::Error` is omitted rather than nulled. A null still costs
/// tokens, and omission is the honest encoding for a measurement this response never took.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionOutcome {
    /// Durable execution identifier.
    pub id: String,
    /// Verdict: passed, failed, error, skipped, or pending.
    pub outcome: ExecutionVerdict,
    /// Durable execution status behind the verdict.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<ExecutionStatus>,
    /// Terminal process exit code, when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    /// Stable failure code, when unsuccessful.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
    /// Whether an idempotency key returned an existing execution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replayed: Option<bool>,
    /// Withheld standard-output bytes, omitted when this response measured no log.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stdout_bytes: Option<usize>,
    /// Withheld standard-error bytes, omitted when this response measured no log.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stderr_bytes: Option<usize>,
    /// Whether bytes were omitted from the beginning of either withheld log.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub truncated: Option<bool>,
    /// Exact follow-up commands that return the withheld detail.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub inspect: Vec<String>,
    /// Bounded log tails, carried only at debug verbosity and above.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub logs: Option<crate::run::RunLogs>,
}

/// Bounded cursor page of durable execution summaries.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionListPage {
    /// Execution summaries in reverse update order.
    pub executions: Vec<ExecutionSummary>,
    /// Opaque cursor for the next older page.
    pub next_cursor: Option<String>,
}

/// System that produced an invocation record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum InvocationSource {
    /// Invocation observed directly by native apoc code.
    Native,
    /// Invocation imported from DevSQL history.
    Devsql,
}

/// User-facing surface where an invocation was accepted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum InvocationSurface {
    /// Command-line invocation.
    Cli,
    /// Model Context Protocol invocation.
    Mcp,
    /// JavaScript Code Mode invocation.
    Code,
}

/// Durable lifecycle status for an invocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum InvocationStatus {
    /// Invocation has started and has no terminal result yet.
    Running,
    /// Invocation completed successfully.
    Succeeded,
    /// Invocation completed unsuccessfully.
    Failed,
    /// Imported or partial invocation lacks enough data for a terminal result.
    Incomplete,
}

/// Scope category used to separate local and global invocation queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum InvocationScopeKind {
    /// Scope is a Git worktree root.
    GitWorktree,
    /// Scope is a current working directory.
    Cwd,
    /// Scope could not be classified.
    Unknown,
}

/// Durable native invocation history record.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct InvocationRecord {
    /// Stable invocation identifier.
    pub id: String,
    /// Parent invocation identifier, when nested.
    pub parent_id: Option<String>,
    /// Durable execution identifier, when the invocation owns or targets one.
    pub execution_id: Option<String>,
    /// System that produced this record.
    pub source: InvocationSource,
    /// Source-native identifier, when imported or bridged.
    pub source_id: Option<String>,
    /// Source-native ordering value, when available.
    pub source_order: Option<i64>,
    /// Source path, database, or stream identifier, when available.
    pub source_path: Option<String>,
    /// Immutable local acceptance order used to stabilize timeline pagination.
    #[serde(default)]
    pub accepted_sequence: u64,
    /// User-facing surface where the invocation was accepted.
    pub surface: InvocationSurface,
    /// Actor label supplied by the caller or agent runtime.
    pub actor: Option<String>,
    /// Whether this invocation was identified as agent-originated.
    pub agent: bool,
    /// Canonical command path such as `execution command`.
    pub command_path: String,
    /// Concise user-facing reason supplied by the caller.
    #[serde(default)]
    pub purpose: Option<String>,
    /// Normalized structured input; secret references remain unresolved and literal values remain.
    #[serde(default)]
    pub normalized_input: serde_json::Value,
    /// Literal searchable text assembled from normalized invocation fields.
    pub search_text: String,
    /// Stable digest of the normalized reusable invocation shape.
    #[serde(default)]
    pub pattern_signature: String,
    /// JSON paths whose values were replaced by type placeholders in the pattern.
    #[serde(default)]
    pub variable_paths: Vec<String>,
    /// Current working directory at invocation time.
    pub cwd: Option<String>,
    /// Query scope category.
    pub scope_kind: InvocationScopeKind,
    /// Query scope key, usually a worktree root or current directory.
    pub scope_key: Option<String>,
    /// Recording session that captured this invocation, when one was active.
    #[serde(default)]
    pub recording_id: Option<String>,
    /// One-based take number within the capturing recording.
    #[serde(default)]
    pub recording_take: Option<u32>,
    /// Invocation start timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Invocation completion timestamp in Unix milliseconds.
    pub completed_at: Option<u64>,
    /// Last record update timestamp in Unix milliseconds.
    pub updated_at: u64,
    /// Current invocation lifecycle status.
    pub status: InvocationStatus,
    /// Terminal process exit code, when applicable.
    pub exit_code: Option<i32>,
    /// Stable terminal error code, when applicable.
    pub error_code: Option<String>,
    /// Human-readable terminal error detail, when applicable.
    pub error: Option<String>,
}

/// Snapshot-stable chronological page of complete sanitized invocation records.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct InvocationTimelinePage {
    /// Complete invocation records in oldest-first acceptance order.
    pub invocations: Vec<InvocationRecord>,
    /// Opaque cursor for the next chronological page in the same snapshot.
    pub next_cursor: Option<String>,
}

/// Compact invocation row returned by query pages.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct InvocationSummary {
    /// Stable invocation identifier.
    pub id: String,
    /// Parent invocation identifier, when nested.
    pub parent_id: Option<String>,
    /// Durable execution identifier, when the invocation owns or targets one.
    pub execution_id: Option<String>,
    /// System that produced this record.
    pub source: InvocationSource,
    /// User-facing surface where the invocation was accepted.
    pub surface: InvocationSurface,
    /// Actor label supplied by the caller or agent runtime.
    pub actor: Option<String>,
    /// Whether this invocation was identified as agent-originated.
    pub agent: bool,
    /// Canonical command path such as `execution command`.
    pub command_path: String,
    /// Concise user-facing reason supplied by the caller.
    pub purpose: Option<String>,
    /// Current working directory at invocation time.
    pub cwd: Option<String>,
    /// Query scope category.
    pub scope_kind: InvocationScopeKind,
    /// Query scope key, usually a worktree root or current directory.
    pub scope_key: Option<String>,
    /// Invocation start timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Invocation completion timestamp in Unix milliseconds.
    pub completed_at: Option<u64>,
    /// Last record update timestamp in Unix milliseconds.
    pub updated_at: u64,
    /// Current invocation lifecycle status.
    pub status: InvocationStatus,
    /// Terminal process exit code, when applicable.
    pub exit_code: Option<i32>,
    /// Stable terminal error code, when applicable.
    pub error_code: Option<String>,
}

/// Bounded cursor page of invocation summaries.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct InvocationPage {
    /// Invocation summaries in reverse update order.
    pub invocations: Vec<InvocationSummary>,
    /// Opaque cursor for the next older page.
    pub next_cursor: Option<String>,
}

/// Hard-bounded SQL result over the sanitized invocation-purpose index.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct HistoryQueryOutput {
    /// Selected output columns. Only `id` and `purpose` are allowed.
    pub columns: Vec<String>,
    /// Compact rows in the same order as `columns`.
    pub rows: Vec<Vec<serde_json::Value>>,
    /// Whether matching rows were omitted by the hard result limit.
    pub truncated: bool,
}

/// Indexed invocation history query.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct InvocationQuery {
    /// Maximum matching invocations.
    pub limit: usize,
    /// Opaque cursor returned by the previous page.
    pub cursor: Option<String>,
    /// Excluded invocation identifier.
    pub exclude_id: Option<String>,
    /// Literal case-insensitive substring matched against `search_text`.
    pub search: Option<String>,
    /// Exact scope category.
    pub scope_kind: Option<InvocationScopeKind>,
    /// Exact scope key.
    pub scope_key: Option<String>,
    /// Exact source system.
    pub source: Option<InvocationSource>,
    /// Exact invocation surface.
    pub surface: Option<InvocationSurface>,
    /// Exact command path.
    pub command_path: Option<String>,
    /// Exact invocation status.
    pub status: Option<InvocationStatus>,
    /// Exact stable terminal error code.
    pub error_code: Option<String>,
    /// Exact actor label.
    pub actor: Option<String>,
    /// Exact durable execution identifier.
    pub execution_id: Option<String>,
    /// Inclusive lower start timestamp in Unix milliseconds.
    pub since_ms: Option<u64>,
    /// Inclusive upper start timestamp in Unix milliseconds.
    pub until_ms: Option<u64>,
}

/// Indexed repeated-invocation pattern query.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct InvocationPatternQuery {
    /// Minimum number of matching invocations required for one pattern.
    pub min_count: usize,
    /// Maximum patterns returned.
    pub limit: usize,
    /// Excluded invocation identifier.
    pub exclude_id: Option<String>,
    /// Exact scope category.
    pub scope_kind: Option<InvocationScopeKind>,
    /// Exact scope key.
    pub scope_key: Option<String>,
    /// Exact source system.
    pub source: Option<InvocationSource>,
    /// Exact canonical command path.
    pub command_path: Option<String>,
    /// Inclusive lower start timestamp in Unix milliseconds.
    pub since_ms: Option<u64>,
    /// Inclusive upper start timestamp in Unix milliseconds.
    pub until_ms: Option<u64>,
}

/// One repeated normalized invocation shape.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct InvocationPattern {
    /// Stable digest of the reusable invocation shape.
    pub signature: String,
    /// Canonical typed command path.
    pub command_path: String,
    /// Matching invocation count.
    pub occurrences: usize,
    /// Successful invocation count.
    pub succeeded: usize,
    /// Failed invocation count.
    pub failed: usize,
    /// Running or incomplete invocation count.
    pub incomplete: usize,
    /// Oldest matching invocation start timestamp.
    pub first_seen: u64,
    /// Newest matching invocation start timestamp.
    pub last_seen: u64,
    /// Input paths represented by type placeholders.
    pub variable_paths: Vec<String>,
    /// Up to three recent matching invocation identifiers.
    pub sample_invocation_ids: Vec<String>,
}

/// Bounded repeated-pattern query result.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct HistoryPatternOutput {
    /// Repeated patterns ordered by occurrence count and recency.
    pub patterns: Vec<InvocationPattern>,
    /// Matching invocations considered by the query.
    pub scanned: usize,
    /// Whether matching patterns were omitted by the result limit.
    pub truncated: bool,
}

/// Durable agent identity and heartbeat scope.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AgentSession {
    /// Stable session identifier.
    pub id: String,
    /// Agent or actor name.
    pub actor: String,
    /// Searchable labels.
    #[serde(default)]
    pub labels: BTreeMap<String, String>,
    /// Session creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Most recent heartbeat in Unix milliseconds.
    pub heartbeat_at: u64,
    /// Absolute expiry in Unix milliseconds.
    pub expires_at: u64,
    /// Whether closure has blocked new work while owned executions terminalize.
    #[serde(default)]
    pub closing: bool,
    /// Whether the session has closed or expired.
    pub closed: bool,
}

/// Durable ownership lease for processes or resources.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Lease {
    /// Stable lease identifier.
    pub id: String,
    /// Owner category.
    pub owner_kind: LeaseOwnerKind,
    /// Execution, session, or persistent owner identifier.
    pub owner_id: String,
    /// Resource keys owned by the lease.
    #[serde(default)]
    pub resources: Vec<String>,
    /// Lease creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Most recent renewal in Unix milliseconds.
    pub renewed_at: u64,
    /// Optional absolute expiry in Unix milliseconds.
    pub expires_at: Option<u64>,
    /// Whether the lease was released or expired.
    pub released: bool,
}

/// Resource categories coordinated by apoc.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ReservationKind {
    /// TCP or UDP port key.
    Port,
    /// Canonical filesystem path.
    Path,
    /// Exact process identity.
    Process,
    /// Device name.
    Device,
    /// Caller-defined coordination key.
    Custom,
}

/// Atomic apoc-local resource claim.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Reservation {
    /// Stable reservation identifier.
    pub id: String,
    /// Resource category.
    pub kind: ReservationKind,
    /// Canonical resource key.
    pub key: String,
    /// Owning lease identifier.
    pub lease_id: String,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Optional absolute expiry in Unix milliseconds.
    pub expires_at: Option<u64>,
    /// Whether a non-apoc owner currently conflicts with the claim.
    pub external_conflict: bool,
    /// Whether the reservation was released or expired.
    pub released: bool,
}

/// Durable result state for an operation receipt.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ReceiptState {
    /// Every requested effect was applied.
    Applied,
    /// At least one effect succeeded and one failed.
    Partial,
    /// No effect was applied.
    Failed,
    /// An effect may have occurred but its result could not be durably recorded.
    Unknown,
}

/// One exact target result within an operation receipt.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OperationTarget {
    /// Canonical target key.
    pub key: String,
    /// Whether the effect was applied.
    pub applied: bool,
    /// Stable error code, when unsuccessful.
    pub error_code: Option<String>,
    /// Human-readable failure detail.
    pub error: Option<String>,
}

/// Idempotent durable receipt for one operation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OperationReceipt {
    /// Stable receipt identifier.
    pub id: String,
    /// Caller-supplied or generated idempotency key.
    pub idempotency_key: String,
    /// Canonical operation name.
    pub operation: String,
    /// Actor that requested the operation.
    pub actor: String,
    /// Owning execution, when applicable.
    pub execution_id: Option<String>,
    /// Receipt outcome.
    pub state: ReceiptState,
    /// Exact target outcomes.
    pub targets: Vec<OperationTarget>,
    /// Intent timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Result timestamp, when recorded.
    pub completed_at: Option<u64>,
}

/// Measured phases from the most recent successful isolated VM boot.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct IsolationBootDiagnostics {
    /// Boot strategy that actually produced the usable VM.
    pub strategy: String,
    /// Cold boot or snapshot restore duration, when measured.
    pub boot_ms: Option<u64>,
    /// In-guest warmup exchange duration, when performed.
    pub warmup_ms: Option<u64>,
    /// Host-to-guest reconnection duration, when measured.
    pub reconnect_ms: Option<u64>,
    /// Total provider-side duration until the VM became usable.
    pub total_ms: u64,
}

/// One atomic snapshot of the built-in isolated VM pool.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct IsolationPoolStatus {
    /// Ready idle VMs.
    pub idle: u64,
    /// Executions waiting for a VM.
    pub waiters: u64,
    /// VMs currently booting or restoring.
    pub in_flight: u64,
    /// Total live or booting VMs owned by the provider.
    pub live: u64,
    /// VMs currently checked out to executions.
    pub checked_out: u64,
    /// Current demand- and memory-bounded idle target.
    pub target: u64,
    /// Configured memory per pooled VM.
    pub per_vm_memory_mb: u64,
    /// Host-wide memory ceiling for the pool.
    pub max_pool_memory_mb: u64,
    /// Whether a drain is currently disposing of pool VMs.
    pub draining: bool,
    /// Whether the provider is shutting the pool down.
    pub shutting_down: bool,
    /// Most recent successful boot measurements.
    pub last_boot: Option<IsolationBootDiagnostics>,
}

/// Structured state of apoc's built-in macOS isolation provider.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct IsolationStatus {
    /// Installed provider build version.
    pub provider_version: String,
    /// Whether a verified bundle has initialized the virtualization backend.
    pub initialized: bool,
    /// Configured bundle path before initialization, when present.
    pub configured_image_path: Option<String>,
    /// Verified bundle path after initialization.
    pub image_path: Option<String>,
    /// Canonical verified image digest, when the bundle has a manifest.
    pub image_digest: Option<String>,
    /// Default virtual CPU count from the initialized bundle.
    pub cpu_count: Option<u64>,
    /// Default guest memory from the initialized bundle.
    pub memory_mb: Option<u64>,
    /// Whether snapshot restore was requested for pooled VMs.
    pub snapshot_restore_enabled: Option<bool>,
    /// Whether the initialized bundle contains a snapshot resource.
    pub snapshot_available: Option<bool>,
    /// Idle lifetime before the pool may drain a VM.
    pub idle_drain_seconds: Option<f64>,
    /// Atomic pool snapshot after initialization.
    pub pool: Option<IsolationPoolStatus>,
    /// True when a drain request found or produced a zero-sized pool.
    pub drained: Option<bool>,
}

/// Durable result of an isolated VM pool mutation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct IsolationMutationResponse {
    /// Durable operation receipt recorded before provider dispatch.
    pub receipt: OperationReceipt,
    /// Resulting pool state when the provider result is known.
    pub status: Option<IsolationStatus>,
    /// Whether this response came from a prior idempotent receipt.
    pub replayed: bool,
}

/// Durable result of importing one verified VM image into apoc-owned storage.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ImageImportResponse {
    /// Durable operation receipt recorded before filesystem mutation.
    pub receipt: OperationReceipt,
    /// Caller-resolved source bundle path.
    pub source_bundle: String,
    /// Digest-addressed apoc bundle path, when import succeeded.
    pub target_bundle: Option<String>,
    /// Verified image digest, when import succeeded.
    pub image_digest: Option<String>,
    /// Number of immutable files copied or confirmed.
    pub files: u64,
    /// Total bytes in the immutable imported files.
    pub bytes: u64,
    /// Whether the verified digest was already present in apoc's image store.
    pub already_present: bool,
    /// Whether this response came from a prior idempotent receipt.
    pub replayed: bool,
}

/// Compact causal record shared by processes, executions, and resources.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CausalEvent {
    /// Monotonic SQLite sequence.
    pub sequence: u64,
    /// Stable event identifier.
    pub id: String,
    /// Event timestamp in Unix milliseconds.
    pub at: u64,
    /// Canonical event kind.
    pub kind: String,
    /// Primary subject key.
    pub subject: String,
    /// Actor responsible for the event.
    pub actor: String,
    /// Correlation scope shared by related events.
    pub correlation_id: String,
    /// Direct causal predecessor, when known.
    pub causation_id: Option<String>,
    /// Owning execution, when applicable.
    pub execution_id: Option<String>,
    /// Owning session, when applicable.
    pub session_id: Option<String>,
    /// Content-addressed snapshot or payload identifier.
    pub payload_id: Option<String>,
    /// Compact structured details kept with the event.
    #[serde(default)]
    pub details: serde_json::Value,
}

/// Metadata for one retained content-addressed payload.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ArtifactMetadata {
    /// Content digest and artifact identifier.
    pub id: String,
    /// Artifact kind.
    pub kind: String,
    /// Owning execution, when applicable.
    pub execution_id: Option<String>,
    /// Stored byte count.
    pub bytes: u64,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last access timestamp in Unix milliseconds.
    pub accessed_at: u64,
    /// Whether retention pruning must preserve the payload.
    pub pinned: bool,
    /// Whether the payload bytes were pruned while metadata was preserved.
    pub pruned: bool,
}

/// Agent-oriented process observation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessInfo {
    /// Stable process identity.
    pub identity: ProcessIdentity,
    /// Operating-system process state.
    pub status: String,
    /// Real user identifier, when available.
    #[serde(default)]
    pub user_id: Option<String>,
    /// Effective user identifier, when available.
    #[serde(default)]
    pub effective_user_id: Option<String>,
    /// Real group identifier, when available.
    #[serde(default)]
    pub group_id: Option<String>,
    /// Login or job-control session identifier, when available.
    #[serde(default)]
    pub session_id: Option<u32>,
    /// CPU use as a percentage of one logical CPU.
    pub cpu_percent: f32,
    /// Accumulated CPU time in milliseconds.
    #[serde(default)]
    pub cpu_time_ms: u64,
    /// Resident memory in bytes.
    pub memory_bytes: u64,
    /// Virtual memory in bytes.
    pub virtual_memory_bytes: u64,
    /// Observed runtime in seconds.
    pub runtime_seconds: u64,
    /// Full command line.
    pub command: Vec<String>,
    /// Current working directory, when available.
    pub cwd: Option<String>,
    /// Total bytes read from storage.
    pub disk_read_bytes: u64,
    /// Total bytes written to storage.
    pub disk_written_bytes: u64,
}

/// Timestamped bounded process-table sample.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessSample {
    /// Observation timestamp in Unix milliseconds.
    pub at: u64,
    /// Processes included in this sample.
    pub processes: Vec<ProcessInfo>,
}

/// Result of waiting for a process selection condition.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessWait {
    /// Original selector.
    pub selector: String,
    /// Requested condition.
    pub condition: String,
    /// Whether the condition was reached.
    pub satisfied: bool,
    /// Wall-clock wait in milliseconds.
    pub elapsed_ms: u64,
    /// Last exact process identities still matching.
    pub processes: Vec<ProcessIdentity>,
}

/// One socket owned by a process.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PortInfo {
    /// Transport protocol.
    pub protocol: String,
    /// Local IP address.
    pub address: String,
    /// Local port.
    pub port: u16,
    /// TCP state, when applicable.
    pub state: Option<String>,
    /// Associated process identifiers.
    pub pids: Vec<u32>,
}

/// One open vnode-backed file descriptor owned by a process.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessFile {
    /// Exact owning process identity.
    pub process: ProcessIdentity,
    /// Numeric file descriptor.
    pub fd: i32,
    /// Native file descriptor type.
    pub kind: String,
    /// Resolved path.
    pub path: String,
    /// Native open flags.
    pub open_flags: u32,
    /// Current file offset.
    pub offset: i64,
}

/// Exact process-liveness probe result.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessProbe {
    /// Requested selector or exact process key.
    pub target: String,
    /// Whether at least one exact identity still exists.
    pub exists: bool,
    /// Matching exact identities.
    pub processes: Vec<ProcessIdentity>,
    /// Observation timestamp in Unix milliseconds.
    pub observed_at: u64,
}

/// One process predicate in a structured boolean query.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ProcessPredicate {
    /// Exact process identifier.
    pub pid: Option<u32>,
    /// Exact parent process identifier.
    pub ppid: Option<u32>,
    /// Exact process-group identifier.
    pub pgid: Option<u32>,
    /// Exact executable name.
    pub name: Option<String>,
    /// Regular expression matched against the executable name.
    pub name_regex: Option<String>,
    /// Regular expression matched against the complete argument vector.
    pub argv_regex: Option<String>,
    /// Required working-directory prefix.
    pub cwd_prefix: Option<String>,
    /// Exact native process state.
    pub status: Option<String>,
    /// Exact real user identifier.
    pub user_id: Option<String>,
    /// Required local TCP or UDP port.
    pub port: Option<u16>,
    /// Port protocol. Defaults to tcp when `port` is present.
    pub protocol: Option<String>,
    /// Actor found in the durable process ledger.
    pub actor: Option<String>,
    /// Execution found in the durable process ledger.
    pub execution_id: Option<String>,
}

/// Structured boolean process query.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessQuery {
    /// Predicates that must all match.
    #[serde(default)]
    pub all: Vec<ProcessPredicate>,
    /// Predicates where at least one must match. Empty means no disjunction.
    #[serde(default)]
    pub any: Vec<ProcessPredicate>,
    /// Predicates that must not match.
    #[serde(default)]
    pub not: Vec<ProcessPredicate>,
    /// Sort field: cpu, memory, runtime, pid, or name.
    pub sort: String,
    /// Maximum result count.
    pub limit: usize,
}

/// Evidence-backed causal answer about one process target.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessInsight {
    /// Query kind: why, impact, owner, related, or changed.
    pub kind: String,
    /// Original target.
    pub target: String,
    /// Exact process observations supporting the answer.
    pub processes: Vec<ProcessInfo>,
    /// Known related executions.
    pub executions: Vec<Execution>,
    /// Known related ownership leases.
    pub leases: Vec<Lease>,
    /// Known related resource reservations.
    pub reservations: Vec<Reservation>,
    /// Relevant compact causal events.
    pub events: Vec<CausalEvent>,
    /// Explicit limits on what apoc can establish from recorded evidence.
    pub limitations: Vec<String>,
}

/// A resolved immutable process selection.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessSelection {
    /// Identifier derived from the resolved process identities.
    pub id: String,
    /// Original selector.
    pub selector: String,
    /// Resolution timestamp in Unix milliseconds.
    pub resolved_at: u64,
    /// Exact process identities selected.
    pub processes: Vec<ProcessIdentity>,
}

/// The apoc controller responsible for one process interaction.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessController {
    /// Unique identifier for this apoc command invocation.
    pub invocation_id: String,
    /// Whether Incurs identified the caller as an agent.
    pub agent: bool,
    /// Caller label from `APOC_ACTOR`, or `agent`/`human`.
    pub actor: String,
    /// apoc process identifier.
    pub controller_pid: u32,
    /// Parent of the apoc process, when available.
    pub parent_pid: Option<u32>,
    /// Working directory from which apoc was invoked.
    pub cwd: Option<String>,
    /// Exact apoc argument vector.
    pub argv: Vec<String>,
    /// Code Mode execution identifier when supplied by the host.
    pub execution_id: Option<String>,
    /// Default response verbosity requested by the invoking process environment.
    #[serde(default)]
    pub verbosity: Option<String>,
    /// Immutable profile selected by an enclosing Code Mode execution.
    #[serde(default)]
    pub profile_selection: Option<ProfileSelection>,
    /// Hook delivery nesting depth propagated through Code Mode.
    #[serde(default)]
    pub hook_depth: u32,
    /// Nonzero inside a decider's own program, whose apoc calls are not sent
    /// back to deciders. Omitted when zero, so stored records keep their shape.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub decider_depth: u32,
}

impl ProcessController {
    /// Captures the current apoc controller without reading target-process environment.
    pub fn capture(agent: bool, execution_id: Option<String>) -> Self {
        Self {
            invocation_id: uuid::Uuid::now_v7().to_string(),
            agent,
            actor: std::env::var("APOC_ACTOR").unwrap_or_else(|_| {
                if agent {
                    "agent".to_string()
                } else {
                    "human".to_string()
                }
            }),
            controller_pid: std::process::id(),
            parent_pid: {
                let pid = unsafe { libc::getppid() };
                (pid > 0).then_some(pid as u32)
            },
            cwd: std::env::current_dir()
                .ok()
                .map(|path| path.to_string_lossy().into_owned()),
            argv: std::env::args().collect(),
            execution_id,
            // Canonicalize here so the deprecated APOC_VIEW still reaches nested Code Mode calls.
            verbosity: Verbosity::from_env()
                .and_then(Result::ok)
                .map(|level| level.as_str().to_string()),
            profile_selection: None,
            hook_depth: 0,
            decider_depth: 0,
        }
    }
}

/// Durable latest-known context for one stable process identity.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessContext {
    /// Stable `BOOT_ID:PID@STARTED_AT_NS` context key.
    pub key: String,
    /// First time apoc observed this identity.
    pub first_observed_at: u64,
    /// Most recent time apoc observed this identity.
    pub last_observed_at: u64,
    /// Number of recorded interactions with this identity.
    pub observations: u64,
    /// Content-addressed latest native process snapshot.
    #[serde(default)]
    pub snapshot_id: Option<String>,
    /// How apoc first gained authority over the process.
    pub origin: String,
    /// Owning execution identifier, when apoc launched the process.
    #[serde(default, alias = "run_id")]
    pub execution_id: Option<String>,
    /// Most recent full native process snapshot.
    pub latest: ProcessInfo,
}

/// One durable interaction with a stable process identity.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessEvent {
    /// Unique event identifier.
    pub id: String,
    /// Stable `BOOT_ID:PID@STARTED_AT_NS` context key.
    pub process_key: String,
    /// Event timestamp in Unix milliseconds.
    pub at: u64,
    /// Canonical operation such as `process.get` or `execution.stop`.
    pub operation: String,
    /// Lifecycle phase: observed, intent, or result.
    pub phase: String,
    /// Selector that resolved the process, when applicable.
    pub selector: Option<String>,
    /// Controller that caused this interaction.
    pub controller: ProcessController,
    /// Managed execution identifier, when applicable.
    #[serde(default, alias = "run_id")]
    pub execution_id: Option<String>,
    /// Operation-specific structured context.
    pub details: serde_json::Value,
}

/// Indexed filters for the cross-process interaction ledger.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ProcessEventQuery {
    /// Maximum newest matching events.
    pub limit: usize,
    /// Exact stable `BOOT_ID:PID@STARTED_AT_NS` key.
    pub process_key: Option<String>,
    /// Any recorded lifetime of this PID.
    pub pid: Option<u32>,
    /// Exact canonical operation.
    pub operation: Option<String>,
    /// Exact lifecycle phase.
    pub phase: Option<String>,
    /// Exact controller actor label.
    pub actor: Option<String>,
    /// Exact controller Code Mode execution identifier.
    pub controller_execution_id: Option<String>,
    /// Exact managed execution identifier.
    pub execution_id: Option<String>,
    /// Inclusive lower event timestamp in Unix milliseconds.
    pub since_ms: Option<u64>,
    /// Inclusive upper event timestamp in Unix milliseconds.
    pub until_ms: Option<u64>,
}

/// Latest process context joined with its bounded event history.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessDossier {
    /// Durable latest-known process context.
    pub context: ProcessContext,
    /// Most recent events, newest first.
    pub events: Vec<ProcessEvent>,
}

/// Result of applying one operation to one process.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ActionResult {
    /// Target identity captured before execution.
    pub process: ProcessIdentity,
    /// Requested action.
    pub action: String,
    /// Whether the operation reached the OS successfully.
    pub applied: bool,
    /// Whether the target exited before the receipt was returned.
    pub exited: bool,
    /// Human-readable failure detail.
    pub error: Option<String>,
}

/// Receipt for a process mutation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ActionReceipt {
    /// Stable receipt identifier.
    pub id: String,
    /// Requested selector.
    pub selector: String,
    /// Operation name.
    pub action: String,
    /// Start timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Completion timestamp in Unix milliseconds.
    pub completed_at: u64,
    /// Per-process outcomes.
    pub results: Vec<ActionResult>,
}

/// Managed process I/O mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum IoMode {
    /// Capture stdout and stderr independently.
    Pipes,
    /// Run under a pseudo-terminal.
    Pty,
}

/// Managed run lifetime.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub(crate) enum RunLifetime {
    /// Stop the process when its owning Code Mode execution ends.
    Execution,
    /// Keep the process alive independently of its creator.
    Persistent,
}

/// Automatic restart behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum RestartPolicy {
    /// Never restart automatically.
    Never,
    /// Restart only after an unsuccessful exit.
    OnFailure,
    /// Restart after every exit until explicitly stopped.
    Always,
}

/// Definition of one managed command.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub(crate) struct RunSpec {
    /// Stable human-readable name.
    pub name: String,
    /// Agent-supplied reason this process exists.
    #[serde(default)]
    pub purpose: Option<String>,
    /// Searchable agent-supplied labels.
    #[serde(default)]
    pub labels: std::collections::BTreeMap<String, String>,
    /// Controller that originally requested this run.
    #[serde(default)]
    pub requested_by: Option<ProcessController>,
    /// Executable followed by arguments.
    pub argv: Vec<String>,
    /// Working directory.
    pub cwd: Option<String>,
    /// Additional environment variables.
    pub env: std::collections::BTreeMap<String, String>,
    /// Resolved secret values held only in memory until process construction.
    #[serde(skip, default)]
    #[schemars(skip)]
    pub resolved_env: std::collections::BTreeMap<String, String>,
    /// Ambient variables removed before applying this run's explicit environment.
    #[serde(default)]
    pub suppressed_env: Vec<String>,
    /// Whether to interpret `argv` as a zsh command string.
    pub shell: bool,
    /// Process I/O mode.
    pub io: IoMode,
    /// Run lifetime.
    pub lifetime: RunLifetime,
    /// Restart policy.
    pub restart: RestartPolicy,
    /// Optional execution deadline.
    pub timeout_ms: Option<u64>,
    /// Number of replicas.
    pub replicas: u32,
    /// Maximum total starts, including the first attempt.
    #[serde(default = "one_attempt")]
    pub max_attempts: u32,
    /// Initial retry delay in milliseconds.
    #[serde(default = "default_retry_backoff")]
    pub retry_backoff_ms: u64,
    /// Maximum retry delay in milliseconds.
    #[serde(default = "default_retry_max_backoff")]
    pub retry_max_backoff_ms: u64,
}

fn one_attempt() -> u32 {
    1
}

fn default_retry_backoff() -> u64 {
    500
}

fn default_retry_max_backoff() -> u64 {
    30_000
}

/// Durable managed-run state.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub(crate) struct ManagedRun {
    /// Stable run identifier.
    pub id: String,
    /// Run definition.
    pub spec: RunSpec,
    /// Current lifecycle state.
    pub status: String,
    /// Current process identities.
    pub processes: Vec<ProcessIdentity>,
    /// Every process lifetime ever owned by this run, including restarts.
    #[serde(default)]
    pub process_history: Vec<ProcessIdentity>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last update timestamp in Unix milliseconds.
    pub updated_at: u64,
    /// Last exit code, when known.
    pub exit_code: Option<i32>,
    /// Standard output log path.
    pub stdout_path: Option<String>,
    /// Standard error log path.
    pub stderr_path: Option<String>,
}

/// Durable reusable JavaScript orchestration.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Recipe {
    /// Unique recipe name.
    pub name: String,
    /// Agent-facing purpose and usage guidance.
    pub description: String,
    /// JavaScript Code Mode program.
    pub code: String,
    /// Optional JSON Schema for the `input` value.
    #[serde(default)]
    pub input_schema: Option<serde_json::Value>,
    /// Optional JSON Schema for the returned value.
    #[serde(default)]
    pub output_schema: Option<serde_json::Value>,
    /// Declared recipe names callable through `recipes.run`.
    #[serde(default)]
    pub dependencies: Vec<String>,
    /// Environment names that must be available before Code Mode starts.
    #[serde(default)]
    pub required_env: Vec<String>,
    /// Agent-facing execution hints.
    #[serde(default)]
    pub annotations: RecipeAnnotations,
    /// Durable namespace in which this recipe is visible.
    #[serde(default = "default_recipe_scope_kind")]
    pub scope_kind: RecipeScopeKind,
    /// Canonical worktree or directory key for a local recipe.
    #[serde(default)]
    pub scope_key: Option<String>,
    /// Digest of the portable recipe definition.
    #[serde(default)]
    pub generation: String,
    /// Optional absolute expiry timestamp in Unix milliseconds.
    #[serde(default)]
    pub expires_at: Option<u64>,
    /// Most recent successful run timestamp in Unix milliseconds.
    #[serde(default)]
    pub last_used_at: Option<u64>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last update timestamp in Unix milliseconds.
    pub updated_at: u64,
    /// Suggestion that originated this definition, when locally adopted.
    #[serde(default)]
    pub origin_suggestion_id: Option<String>,
    /// Recording that emitted this definition, when promoted from a capture session.
    #[serde(default)]
    pub origin_recording_id: Option<String>,
}

/// Recipe visibility namespace.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RecipeScopeKind {
    /// Visible to every invocation for the current user.
    Global,
    /// Visible within one canonical Git worktree.
    GitWorktree,
    /// Visible within one canonical current directory.
    Cwd,
}

fn default_recipe_scope_kind() -> RecipeScopeKind {
    RecipeScopeKind::Global
}

/// Optional recipe safety and replay hints.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct RecipeAnnotations {
    /// Recipe only reads external state.
    #[serde(default)]
    pub read_only: Option<bool>,
    /// Recipe may change or delete external state.
    #[serde(default)]
    pub destructive: Option<bool>,
    /// Recipe is safe to retry with one caller key.
    #[serde(default)]
    pub idempotent: Option<bool>,
    /// Recipe can act on unrestricted external resources.
    #[serde(default)]
    pub open_world: Option<bool>,
}

/// Portable recipe definition without machine-local scope or lifecycle state.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecipePortableDefinition {
    /// Dotted recipe name.
    pub name: String,
    /// Agent-facing purpose and usage guidance.
    pub description: String,
    /// JavaScript Code Mode body.
    pub code: String,
    /// Optional input JSON Schema.
    #[serde(default)]
    pub input_schema: Option<serde_json::Value>,
    /// Optional output JSON Schema.
    #[serde(default)]
    pub output_schema: Option<serde_json::Value>,
    /// Declared transitive recipe names.
    #[serde(default)]
    pub dependencies: Vec<String>,
    /// Required environment names; values and secret references are never exported.
    #[serde(default)]
    pub required_env: Vec<String>,
    /// Agent-facing execution hints.
    #[serde(default)]
    pub annotations: RecipeAnnotations,
    /// Digest of this portable definition.
    pub generation: String,
}

/// Lifecycle state of an immutable recipe suggestion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RecipeSuggestionStatus {
    /// Candidate is available for explicit adoption.
    Pending,
    /// Candidate was adopted into an executable recipe.
    Adopted,
}

/// Exact chronological evidence interval supporting one recipe suggestion.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecipeEvidenceRange {
    /// First invocation identifier, inclusive.
    pub start_id: String,
    /// Last invocation identifier, inclusive.
    pub end_id: String,
    /// Exact ordered invocation identifiers captured when suggested.
    pub invocation_ids: Vec<String>,
}

/// Immutable, non-executable candidate for one reusable recipe.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecipeSuggestion {
    /// Stable suggestion identifier.
    pub id: String,
    /// Exact portable candidate supplied by the caller LLM.
    pub candidate: RecipePortableDefinition,
    /// Repeated positive history intervals; at least two are required.
    pub positive_evidence: Vec<RecipeEvidenceRange>,
    /// Optional counterexample intervals.
    #[serde(default)]
    pub counterexamples: Vec<RecipeEvidenceRange>,
    /// Caller-supplied explanation of the reusable pattern.
    pub rationale: String,
    /// Scope in which evidence was interpreted and adoption will occur.
    pub scope_kind: RecipeScopeKind,
    /// Canonical local scope key, when applicable.
    pub scope_key: Option<String>,
    /// Current adoption state.
    pub status: RecipeSuggestionStatus,
    /// Adopted recipe generation, when adopted.
    pub adopted_generation: Option<String>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Adoption timestamp in Unix milliseconds.
    pub adopted_at: Option<u64>,
}

/// Versioned portable recipe namespace.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecipeBundleV1 {
    /// Bundle schema version. Version 1 is the only accepted value.
    pub schema_version: u32,
    /// Dotted namespace or prefix selected for export.
    pub namespace: String,
    /// Selected recipes and every transitive dependency.
    pub recipes: Vec<RecipePortableDefinition>,
}

/// Lifecycle state of one durable recording session.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RecordingStatus {
    /// Session is capturing invocations in its scope.
    Active,
    /// Session was stopped and promoted to a recipe or suggestion.
    Stopped,
    /// Session was discarded without emitting anything.
    Discarded,
}

/// Explicit parameter holder declared while a recording was active.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecordingParam {
    /// Recipe input name this value becomes.
    pub name: String,
    /// Exact recorded value replaced wherever it appears.
    pub value: serde_json::Value,
}

/// One bracketed capture pass over ordinary apoc work.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecordingTake {
    /// One-based take number within this recording.
    pub index: u32,
    /// Take start timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Take stop timestamp in Unix milliseconds.
    pub stopped_at: Option<u64>,
    /// Explicit holders declared during this take.
    #[serde(default)]
    pub params: Vec<RecordingParam>,
}

/// One transcribed Code Mode call site derived from a recorded invocation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecordingStep {
    /// Source invocation identifier.
    pub invocation_id: String,
    /// Take that captured this step.
    pub take: u32,
    /// Canonical command path such as `execution command`.
    pub command_path: String,
    /// Code Mode host method such as `apoc.execution_command`.
    pub method: String,
    /// Merged recorded arguments, options, and purpose.
    pub input: serde_json::Value,
    /// Stable digest of the normalized reusable invocation shape.
    pub pattern_signature: String,
    /// Step-relative JSON paths whose recorded values varied.
    #[serde(default)]
    pub variable_paths: Vec<String>,
}

/// Durable capture session that promotes recorded invocations into one recipe.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Recording {
    /// Stable recording identifier.
    pub id: String,
    /// Dotted recipe name this recording becomes.
    pub name: String,
    /// Current capture state.
    pub status: RecordingStatus,
    /// Durable namespace in which the emitted recipe is visible.
    pub scope_kind: RecipeScopeKind,
    /// Canonical worktree or directory key for a local recording.
    pub scope_key: Option<String>,
    /// Ordered capture passes.
    pub takes: Vec<RecordingTake>,
    /// Step-relative JSON paths forced to stay literal.
    #[serde(default)]
    pub literal_paths: Vec<String>,
    /// Invocation identifiers excluded from emission.
    #[serde(default)]
    pub skipped: Vec<String>,
    /// Exact chronological evidence resolved when the recording stopped.
    #[serde(default)]
    pub evidence: Vec<RecipeEvidenceRange>,
    /// Emitted recipe generation, when stopped with a name.
    #[serde(default)]
    pub recipe_generation: Option<String>,
    /// Emitted suggestion identifier, when stopped as a candidate.
    #[serde(default)]
    pub suggestion_id: Option<String>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last update timestamp in Unix milliseconds.
    pub updated_at: u64,
}

/// One recording and the call sites it would emit today.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecordingDetail {
    /// Durable recording record.
    pub recording: Recording,
    /// Ordered call sites after exclusion rules are applied.
    pub steps: Vec<RecordingStep>,
}

/// Result of stopping one recording.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecordingStopOutput {
    /// Durable recording record in its stopped state.
    pub recording: Recording,
    /// Recipe written when a name was supplied.
    pub recipe: Option<Recipe>,
    /// Non-executable candidate written when `--suggest` was supplied.
    pub suggestion: Option<RecipeSuggestion>,
}

/// Registered provider transport.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ProviderKind {
    /// Command graph compiled into apoc.
    Builtin,
    /// Streamable HTTP MCP server.
    McpHttp,
    /// MCP server launched and supervised over standard I/O.
    McpStdio,
    /// OpenAPI document plus authenticated HTTP base URL.
    OpenApi,
}

/// Durable capability-provider configuration.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProviderConfig {
    /// JavaScript namespace exposed in Code Mode.
    pub name: String,
    /// Provider transport.
    pub kind: ProviderKind,
    /// MCP endpoint or OpenAPI specification URL.
    #[serde(default)]
    pub url: Option<String>,
    /// OpenAPI request base URL. Unused by MCP.
    #[serde(default)]
    pub base_url: Option<String>,
    /// Executable used by an MCP stdio provider.
    #[serde(default)]
    pub command: Option<String>,
    /// Exact arguments passed to an MCP stdio provider.
    #[serde(default)]
    pub args: Vec<String>,
    /// Working directory for an MCP stdio provider.
    #[serde(default)]
    pub cwd: Option<String>,
    /// Literal environment values for an MCP stdio provider.
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// Environment values resolved from secret references when the provider starts.
    #[serde(default)]
    pub secret_env: BTreeMap<String, SecretRef>,
    /// Non-secret static HTTP headers.
    #[serde(default)]
    pub headers: std::collections::BTreeMap<String, String>,
    /// HTTP headers resolved from secret references at connection time.
    #[serde(default)]
    pub secret_headers: BTreeMap<String, SecretRef>,
    /// Whether this provider ignores, optionally uses, or requires a selected profile.
    #[serde(default)]
    pub profile_mode: ProfileMode,
    /// Provider environment name to profile variable name mappings.
    #[serde(default)]
    pub profile_env: BTreeMap<String, String>,
    /// Provider HTTP header name to profile variable name mappings.
    #[serde(default)]
    pub profile_headers: BTreeMap<String, String>,
    /// Model-facing usage guidance.
    #[serde(default)]
    pub instructions: Option<String>,
    /// Whether the provider is included in new capability snapshots.
    #[serde(default = "provider_enabled")]
    pub enabled: bool,
    /// Content digest of the provider configuration and discovered capabilities.
    #[serde(default)]
    pub generation: String,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last update timestamp in Unix milliseconds.
    pub updated_at: u64,
}

fn provider_enabled() -> bool {
    true
}

/// Returns whether a provider name is a valid JavaScript namespace binding.
pub fn valid_provider_name(value: &str) -> bool {
    let mut characters = value.chars();
    let Some(first) = characters.next() else {
        return false;
    };
    (first.is_ascii_alphabetic() || matches!(first, '_' | '$'))
        && characters
            .all(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '$'))
}

/// Backward-compatible name for a provider transport.
pub type ConnectorKind = ProviderKind;

/// Backward-compatible name for a provider configuration.
pub type ConnectorConfig = ProviderConfig;

/// Behavioral annotations used when coordinating one provider capability.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct CapabilityAnnotations {
    /// Whether the capability is observational only.
    pub read_only: Option<bool>,
    /// Whether the capability may perform destructive updates.
    pub destructive: Option<bool>,
    /// Whether repeating the same downstream key adds no effect.
    pub idempotent: Option<bool>,
    /// Whether the capability may affect an external system or person.
    pub open_world: Option<bool>,
}

/// Strength of the identity available for a capability target.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum IdentityMode {
    /// A versioned exact identity is resolved before mutation.
    Exact,
    /// A provider-defined stable resource key is available.
    Stable,
    /// No target identity stronger than the provider is available.
    Opaque,
}

/// Resource-locking behavior for one capability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum CoordinationMode {
    /// Independent resolved resource keys can execute concurrently.
    Resource,
    /// Mutations serialize across the provider.
    Provider,
    /// The capability is read-only and needs no mutation coordination.
    None,
}

/// Postcondition strength available for one capability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum VerificationMode {
    /// The provider reads the affected state back after mutation.
    Readback,
    /// The provider returns a downstream receipt without state readback.
    Receipt,
    /// No postcondition verification is available.
    Unavailable,
}

/// One progressively discoverable provider capability.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CapabilityDescriptor {
    /// Provider namespace.
    pub provider: String,
    /// Method name within the provider namespace.
    pub method: String,
    /// Human-readable capability description.
    pub description: Option<String>,
    /// JSON Schema accepted by the method.
    pub input_schema: serde_json::Value,
    /// JSON Schema returned by the method, when declared.
    pub output_schema: Option<serde_json::Value>,
    /// Truthful behavioral annotations.
    pub annotations: CapabilityAnnotations,
    /// Target identity strength.
    pub identity_mode: IdentityMode,
    /// Mutation coordination behavior.
    pub coordination_mode: CoordinationMode,
    /// Postcondition verification behavior.
    pub verification_mode: VerificationMode,
    /// Immutable provider capability generation.
    pub generation: String,
}

/// Provider-specific stable identity for one controlled resource.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ResourceIdentity {
    /// Provider namespace.
    pub provider: String,
    /// Provider-defined resource category.
    pub kind: String,
    /// Canonical resource key.
    pub key: String,
    /// Optional version or concurrency token.
    pub version: Option<String>,
    /// Identity strength available to apoc.
    pub mode: IdentityMode,
}

/// Current Unix timestamp in milliseconds.
pub fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

fn is_zero(value: &u32) -> bool {
    *value == 0
}

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

    #[test]
    fn publishes_the_v8_execution_contract() {
        assert_eq!(SCHEMA_VERSION, 8);
        let schema = serde_json::to_value(schemars::schema_for!(ExecutionSpec)).unwrap();
        let text = serde_json::to_string(&schema).unwrap();
        assert!(text.contains("schema_version"));
        assert!(text.contains("idempotency_key"));
        assert!(text.contains("javascript"));
        assert!(text.contains("max_attempts"));
        assert!(text.contains("progress_timeout_ms"));
        assert!(text.contains("memory_bytes"));
        assert!(text.contains("cpu_percent"));
        assert!(text.contains("cpu_time_ms"));
        assert!(text.contains("commands"));
        assert!(text.contains("parallel"));
        assert!(text.contains("pipeline"));
        assert!(text.contains("max_parallel"));
        assert!(text.contains("pipefail"));
        assert!(text.contains("profile_selection"));
        assert!(!text.contains("environment_generations"));
        assert!(text.contains("backend"));
        assert!(text.contains("isolated"));
        assert!(text.contains("image"));
        assert!(text.contains("workspace"));
        assert!(text.contains("guest_cwd"));
        assert!(text.contains("memory_mb"));
        assert!(text.contains("cpu_count"));
        assert!(text.contains("pids_max"));
        assert!(text.contains("network"));
        assert!(text.contains("exports"));
        assert!(text.contains("telemetry"));
        assert!(text.contains("sample"));
    }

    #[test]
    fn preserves_a_provider_backend_in_the_execution_contract() {
        let mut value = serde_json::to_value(asserted(None, None).spec).unwrap();
        value["backend"] = serde_json::json!({
            "kind": "provider",
            "name": "exeggutor",
            "generation": "sha256:provider-v1",
            "options": { "image": "local" }
        });

        let spec = serde_json::from_value::<ExecutionSpec>(value).unwrap();
        let encoded = serde_json::to_value(spec).unwrap();

        assert_eq!(
            encoded.pointer("/backend/kind"),
            Some(&serde_json::json!("provider"))
        );
        assert_eq!(
            encoded.pointer("/backend/name"),
            Some(&serde_json::json!("exeggutor"))
        );
        assert_eq!(
            encoded.pointer("/backend/generation"),
            Some(&serde_json::json!("sha256:provider-v1"))
        );
        assert_eq!(
            encoded.pointer("/backend/options/image"),
            Some(&serde_json::json!("local"))
        );
    }

    #[test]
    fn preserves_an_isolated_backend_in_the_execution_contract() {
        let mut value = serde_json::to_value(asserted(None, None).spec).unwrap();
        value["backend"] = serde_json::json!({
            "kind": "isolated",
            "isolation": {
                "image": "local",
                "workspace": "read_write",
                "guest_cwd": "/workspace/src",
                "memory_mb": 2048,
                "cpu_count": 4,
                "pids_max": 256,
                "network": "none",
                "exports": []
            }
        });

        let spec = serde_json::from_value::<ExecutionSpec>(value).unwrap();
        let encoded = serde_json::to_value(spec).unwrap();

        assert_eq!(
            encoded.pointer("/backend/kind"),
            Some(&serde_json::json!("isolated"))
        );
        assert_eq!(
            encoded.pointer("/backend/isolation/guest_cwd"),
            Some(&serde_json::json!("/workspace/src"))
        );
        assert_eq!(
            encoded.pointer("/backend/isolation/memory_mb"),
            Some(&serde_json::json!(2048))
        );
    }

    /// Builds a completed execution that declared the given expectation.
    fn asserted(expect: Option<PollCondition>, result: Option<serde_json::Value>) -> Execution {
        Execution {
            id: "execution".to_string(),
            parent_id: None,
            session_id: None,
            spec: ExecutionSpec {
                schema_version: SCHEMA_VERSION,
                idempotency_key: None,
                name: "assertion".to_string(),
                purpose: Some("Judging a declared expectation.".to_string()),
                labels: BTreeMap::new(),
                program: ExecutionProgram::Command {
                    argv: vec!["/bin/echo".to_string()],
                    shell: false,
                },
                backend: ExecutionBackendSpec::default(),
                workspace: WorkspaceContext::default(),
                env: BTreeMap::new(),
                secrets: BTreeMap::new(),
                profile_selection: None,
                io: IoMode::Pipes,
                owner_kind: LeaseOwnerKind::Execution,
                owner_id: None,
                expires_at: None,
                retry: RetryPolicy::default(),
                budget: ExecutionBudget::default(),
                telemetry: TelemetryPolicy::default(),
                expect,
            },
            status: ExecutionStatus::Completed,
            passes: Vec::new(),
            attempts: Vec::new(),
            created_at: 0,
            updated_at: 0,
            last_progress_at: 0,
            result,
        }
    }

    fn stdout_regex() -> Option<PollCondition> {
        Some(PollCondition::StdoutRegex {
            pattern: "ready".to_string(),
        })
    }

    #[test]
    fn an_unevaluated_expectation_is_a_fault_rather_than_a_pass() {
        // A clean exit whose declared assertion reached no judgment is the JUnit `error` case:
        // the harness never answered. Reporting `passed` here would make a red test look green.
        let unevaluated = asserted(stdout_regex(), Some(serde_json::json!({"exit_code": 0})));
        assert_eq!(unevaluated.expectation(), ExpectationState::Unevaluated);
        assert_eq!(
            ExecutionVerdict::of_execution(&unevaluated),
            ExecutionVerdict::Error
        );

        // The same record with no expectation declared asserted nothing and simply passed.
        let undeclared = asserted(None, Some(serde_json::json!({"exit_code": 0})));
        assert_eq!(undeclared.expectation(), ExpectationState::NotDeclared);
        assert_eq!(
            ExecutionVerdict::of_execution(&undeclared),
            ExecutionVerdict::Passed
        );
    }

    #[test]
    fn recording_a_judgment_never_silently_does_nothing() {
        // Every shape a durable result can hold must still accept the judgment. A recorder that
        // can no-op is the same silent pass the verdict mapping above refuses.
        for result in [
            None,
            Some(serde_json::Value::Null),
            Some(serde_json::json!("opaque")),
            Some(serde_json::json!({"exit_code": 0})),
        ] {
            let mut execution = asserted(stdout_regex(), result.clone());
            execution.record_expectation(false, Some("regex failed".to_string()));
            assert_eq!(
                execution.expectation(),
                ExpectationState::Unmet,
                "{result:?} lost its judgment"
            );
            assert_eq!(
                ExecutionVerdict::of_execution(&execution),
                ExecutionVerdict::Failed
            );
        }

        // A displaced non-object result is preserved rather than discarded.
        let mut opaque = asserted(stdout_regex(), Some(serde_json::json!("opaque")));
        opaque.record_expectation(true, None);
        assert_eq!(opaque.result.as_ref().unwrap()[RESULT_DISPLACED], "opaque");
        assert_eq!(
            ExecutionVerdict::of_execution(&opaque),
            ExecutionVerdict::Passed
        );
    }

    #[test]
    fn a_skipped_command_outranks_every_other_signal() {
        let mut skipped = asserted(stdout_regex(), Some(serde_json::json!({"skipped": true})));
        assert_eq!(
            ExecutionVerdict::of_execution(&skipped),
            ExecutionVerdict::Skipped
        );
        skipped.status = ExecutionStatus::Failed;
        assert_eq!(
            ExecutionVerdict::of_execution(&skipped),
            ExecutionVerdict::Skipped,
            "a command that never launched cannot have failed its assertion"
        );
    }

    #[test]
    fn a_command_group_that_counted_its_children_reached_a_verdict() {
        // A group has no exit code of its own. Judging it by one would report every batch with
        // a failing command as an apoc fault, sending the caller to look for a broken harness.
        let mut group = asserted(None, Some(serde_json::json!({"counts": {"failed": 1}})));
        group.status = ExecutionStatus::Failed;
        assert_eq!(
            ExecutionVerdict::of_execution(&group),
            ExecutionVerdict::Failed
        );

        // A group that failed before counting anything never reached a verdict.
        let mut broken = asserted(
            None,
            Some(serde_json::json!({"error_code": "EXECUTION_CLEANUP_FAILED"})),
        );
        broken.status = ExecutionStatus::Failed;
        assert_eq!(
            ExecutionVerdict::of_execution(&broken),
            ExecutionVerdict::Error
        );
    }

    #[test]
    fn a_deprecated_view_keeps_the_contract_it_named() {
        // `outcome` asked for the collapsed verdict. Resolving it to a wider level would hand
        // an existing caller more context than it ever requested.
        assert_eq!(
            Verbosity::parse_view("outcome").unwrap(),
            Verbosity::DEFAULT
        );
        assert_eq!(Verbosity::parse_view("full").unwrap(), Verbosity::Trace);
    }

    #[test]
    fn defaults_and_verbosity_cover_every_public_value() {
        assert_eq!(
            serde_json::to_value(PollSchedule::default()).unwrap(),
            serde_json::json!({ "kind": "fixed_delay", "interval_ms": 1000 })
        );

        for (level, name) in [
            (Verbosity::Off, "off"),
            (Verbosity::Error, "error"),
            (Verbosity::Warn, "warn"),
            (Verbosity::Info, "info"),
            (Verbosity::Debug, "debug"),
            (Verbosity::Trace, "trace"),
        ] {
            assert_eq!(level.as_str(), name);
        }
        assert_eq!(Verbosity::parse(" silent ").unwrap(), Verbosity::Off);
        assert!(Verbosity::parse("verbose").unwrap_err().contains("verbose"));
        assert!(
            Verbosity::parse_view("debug")
                .unwrap_err()
                .contains("debug")
        );
        assert_eq!(Verbosity::Info.shift(0), Verbosity::Info);
        assert_eq!(Verbosity::Off.shift(-10), Verbosity::Off);
        assert_eq!(Verbosity::Trace.shift(10), Verbosity::Trace);
        assert_eq!(Verbosity::Warn.shift(1), Verbosity::Info);
        assert_eq!(Verbosity::Debug.shift(-2), Verbosity::Error);

        let legacy: RunSpec = serde_json::from_value(serde_json::json!({
            "name": "legacy",
            "argv": ["true"],
            "cwd": null,
            "env": {},
            "shell": false,
            "io": "pipes",
            "lifetime": "persistent",
            "restart": "never",
            "timeout_ms": null,
            "replicas": 1
        }))
        .unwrap();
        assert_eq!(legacy.max_attempts, 1);
        assert_eq!(legacy.retry_backoff_ms, 500);
        assert_eq!(legacy.retry_max_backoff_ms, 30_000);
    }

    #[test]
    fn a_completed_nonzero_command_is_a_failed_verdict() {
        let execution = asserted(None, Some(serde_json::json!({"exit_code": 9})));
        assert_eq!(
            ExecutionVerdict::of_execution(&execution),
            ExecutionVerdict::Failed
        );
    }

    #[test]
    fn a_declared_nonzero_exit_can_pass_its_expectation() {
        let mut execution = asserted(
            Some(PollCondition::ExitCode { codes: vec![1] }),
            Some(serde_json::json!({"exit_code": 1})),
        );
        execution.record_expectation(true, None);

        assert_eq!(execution.expectation(), ExpectationState::Met);
        assert_eq!(
            ExecutionVerdict::of_execution(&execution),
            ExecutionVerdict::Passed
        );
    }

    #[test]
    fn retry_policy_is_finite_by_default() {
        let retry = RetryPolicy::default();
        assert_eq!(retry.max_attempts, 1);
        assert!(retry.max_backoff_ms >= retry.backoff_ms);
    }

    #[test]
    fn publishes_the_v3_provider_contract() {
        assert_eq!(SCHEMA_VERSION, 8);
        let schema = serde_json::to_value(schemars::schema_for!(ProviderConfig)).unwrap();
        let text = serde_json::to_string(&schema).unwrap();
        assert!(text.contains("mcp_stdio"));
        assert!(text.contains("secret_headers"));
        assert!(text.contains("secret_env"));
        assert!(text.contains("command"));
        assert!(text.contains("profile_mode"));
        assert!(text.contains("profile_headers"));
        assert!(text.contains("profile_env"));

        let capability = CapabilityDescriptor {
            provider: "fixture".to_string(),
            method: "apply".to_string(),
            description: Some("Apply one fixture mutation.".to_string()),
            input_schema: serde_json::json!({"type": "object"}),
            output_schema: None,
            annotations: CapabilityAnnotations {
                destructive: Some(true),
                ..CapabilityAnnotations::default()
            },
            identity_mode: IdentityMode::Opaque,
            coordination_mode: CoordinationMode::Provider,
            verification_mode: VerificationMode::Unavailable,
            generation: "fixture-generation".to_string(),
        };
        assert_eq!(capability.coordination_mode, CoordinationMode::Provider);
    }

    #[test]
    fn provider_names_are_javascript_namespace_bindings() {
        assert!(valid_provider_name("macos"));
        assert!(valid_provider_name("github_v2"));
        assert!(valid_provider_name("$host"));
        assert!(!valid_provider_name("mac-os"));
        assert!(!valid_provider_name("2mac"));
        assert!(!valid_provider_name(""));
    }
}