adk-kernel 3.0.0

Agent kernel for ADK-Rust: a resident supervisor with a process model, wake sources, an event bus and a control plane over durable runs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
//! The supervisor (spec 3.2 §7.2).
//!
//! A [`Kernel`] composes the background machinery `adk-rust serve` already builds (§6 D-9)
//! and adds a worker per queue class, the scheduler, the wake sources, the process table,
//! the event bus and the control plane:
//!
//! | Kernel part | Built from |
//! |---|---|
//! | Workers | One `DurableWorker` per [`QueueClass`], each with [`KernelConfig::worker_config`]: `on_governance_refusal: Park` (§10 S3), the class's poll interval, the S1 `WorkerHooks` turned into [`KernelEvent`]s, and the targets registered with [`KernelBuilder::agent`] (the harness runner as `adk-rust` and `harness.goal`), on [`KernelConfig::clock`] |
//! | Scheduler | `DurableScheduler::new(schedules, runs).with_governance(..).with_clock(..)`, ticking every [`KernelConfig::scheduler_tick`] on [`KernelConfig::clock`] |
//! | Wake sources | [`KernelBuilder::wake_source`], [`KernelBuilder::trigger`] and [`KernelBuilder::queue_ingress`], routed by the [`WakeRouter`] (§7.4) |
//! | Approvals | `StoreApprovalService::with_run_store`, so a decision wakes the parked run; the service's `tick` on the kernel's clock for expiries |
//! | Kill switch | [`KernelConfig::governance`]: `GovernanceControl::mirrored` with a 250 ms poll on multi-replica ([`KernelConfig::mirrored_governance`], K-I8) |
//! | Control plane | [`ControlPlane`] over [`KernelConfig::control`] (§7.11) |
//! | `/proc` (feature `proc`) | `KernelBuilder::ledger`: a sink on the bus writes every event's ledger row; the hosted runtime's `ProgressSource` gets the ledger at start; with `proc-baselines` the maintenance tick enqueues the daily `kernel.proc` pass, and [`KernelBuilder::observation_audience`] puts a partition's observations to a person as agenda questions (§7.10) |
//!
//! Lifecycle: [`pause`](Kernel::pause) shuts each worker's claim loop down and lets running
//! processes finish their attempt; [`drain`](Kernel::drain) suspends running processes at
//! their next checkpoint through S1's suspend path, then shuts the loops down, and on
//! timeout aborts them so their leases lapse; [`stop`](Kernel::stop) also stops drivers and
//! closes the control plane. A `SIGTERM` is `drain(30 s)` then `stop`
//! ([`shutdown_on_signal`](Kernel::shutdown_on_signal)). Nothing is lost on a hard kill:
//! leases expire and another claim resumes from the checkpoint.
//!
//! [`freeze`](Kernel::freeze) calls `GovernanceControl::freeze_recorded`; parking is the
//! worker's (§10 S3), so every replica's worker parks its own running processes
//! `Waiting` with `ParkReason::Frozen` as its mirrored control observes the freeze.
//! [`unfreeze`](Kernel::unfreeze) calls `unfreeze_recorded` and wakes exactly the
//! freeze-parked processes (K-I21). The kernel registers itself as the
//! `GovernanceController`'s `FreezeDelegate` (§10 S4), so `POST /api/admin/freeze` parks.

use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use std::sync::{Arc, RwLock};
use std::time::Duration;

use adk_core::audit_log::{AuditActor, AuditTrail};
use adk_core::queue_source::QueueIngress;
use adk_core::schedule::Jitter;
use adk_core::{
    ApprovalPolicy, ApprovalService, ApproverSelector, Clock, DurableRunStore, Enqueued,
    GovernanceControl, GovernanceMirrorConfig, GovernanceStateStore, ScheduleStore, SpendLedger,
    SystemClock,
};
use adk_runner::Runner;
use adk_server::background::{
    DurableScheduler, DurableSubagents, DurableWorker, DurableWorkerConfig, SubagentBackend,
    SubagentConfig, WorkflowExecutor, WorkflowRunContext, WorkflowState,
};
use adk_server::rest::{FreezeDelegate, FreezeReport};
use adk_session::SessionService;
use async_trait::async_trait;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;

use crate::agenda::{Agenda, AgendaHandle, AgendaStore, ObservationAudience, ProactivityPolicy};
use crate::audit;
use crate::bus::{EventBus, EventSink, EventSubscriber, KernelEvent};
use crate::consolidation::{ConsolidationExecutor, ConsolidationTicker, Consolidator};
use crate::control::{ControlPlane, ControlPlaneConfig};
use crate::error::{KernelError, Result};
use crate::inventory::{InventoryTrigger, InventoryWarning, KernelInventory};
use crate::partition::{PartitionId, Partitions};
#[cfg(feature = "proc")]
use crate::proc::{Ledger, LedgerEventSink};
use crate::process::{ProcessHandle, ProcessTable, ProgressSource, Suspension};
use crate::sched::{QueueClass, QuietHours, Quotas};
use crate::stores::{
    InMemoryAgendaStore, InMemoryCronWatermarkStore, InMemoryProcessStore, ProcessStore,
};
use crate::stores::{KernelStores, ProcessFilter, StoreOrigin, StoreUse};
use crate::supervise::{KernelHooks, Supervision};
use crate::wake::{
    CronWakeSource, FileWakeSource, KernelWakeExecutor, RunFinishedWakeSource, Trigger, Wake,
    WakeEvent, WakeRouter, WakeSource, keys,
};
use crate::watermark::{CronWatermarkStore, SourceWatermark};

/// How the kernel runs (spec 3.2 §7.2).
///
/// `proactivity`, `quiet_hours` and `quotas` apply to every partition (§7.5, §7.9); the
/// partition records of phase 3 carry their own.
///
/// # Example
///
/// ```rust
/// use std::time::Duration;
/// use adk_kernel::{KernelConfig, QueueClass};
///
/// let config = KernelConfig::default().with_scheduler_tick(Duration::from_millis(500));
/// assert_eq!(config.app_name, "adk-rust");
/// assert_eq!(config.queues, QueueClass::defaults());
/// let background = config.worker_config(&QueueClass::Background);
/// assert_eq!(background.queue, "background");
/// assert_eq!(background.poll_interval, Duration::from_secs(2));
/// // No control plane unless one is configured.
/// assert_eq!((config.control.socket, config.control.http), (None, None));
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct KernelConfig {
    /// The application runs belong to. Defaults to `adk-rust`.
    pub app_name: String,
    /// The kernel home: stores, socket and logs. Defaults to `dirs::config_dir()/adk-rust`.
    pub home: PathBuf,
    /// The queue classes, one worker each (spec 3.2 §7.9). Defaults to interactive,
    /// background and maintenance. Under a kernel, runs submitted without a queue — through
    /// `/api/runs` or `adk-rust serve`'s background state — land on `interactive`; there is
    /// no worker for the `default` queue.
    pub queues: Vec<QueueClass>,
    /// The worker configuration every queue's worker starts from
    /// (`adk-server/src/background/worker.rs`); [`worker_config`](Self::worker_config) sets
    /// the queue and poll interval per class. Its `on_governance_refusal` is `Park` (§10 S3).
    pub worker: DurableWorkerConfig,
    /// How often the scheduler looks for due schedules. Defaults to 1 second.
    pub scheduler_tick: Duration,
    /// The kill switch: `GovernanceControl::mirrored(..)` on multi-replica, with a poll of at
    /// most 250 ms (K-I8). Defaults to a local control.
    pub governance: GovernanceControl,
    /// The control plane: socket path, HTTP bind and the caller's
    /// `RequestContextExtractor` (spec 3.2 §7.11). Defaults to none, neither a socket nor
    /// an HTTP bind, so a kernel built from the defaults never takes the socket of a kernel
    /// already serving the same home; `with_control(ControlPlaneConfig::default())` serves
    /// the socket at [`home`](Self::home), as `adk-rust up` does.
    pub control: ControlPlaneConfig,
    /// Refuse to start a driver where no sandbox enforcer exists (spec 3.2 §7.7). Defaults
    /// to `false`.
    pub fail_if_sandbox_unavailable: bool,
    /// The time the kernel reads: [`Wake::At`] times and wake-set expiry, the scheduler's
    /// due schedules, process ages, spend days, and the age at which the workers prune
    /// finished runs. Defaults to `SystemClock`. Give the run store the same clock
    /// (`SqliteRunStore::with_clock`), since it decides leases and `not_before` and stamps
    /// the times the workers compare with it.
    pub clock: Arc<dyn Clock>,
    /// The proactivity limits of every partition: open proposals, the daily proactive
    /// budget, quiet hours, how proposals are approved, the consolidation tick (spec 3.2
    /// §7.5). Defaults to [`ProactivityPolicy::default`].
    pub proactivity: ProactivityPolicy,
    /// A local-time window in which no proactive or maintenance process starts, beside the
    /// proactivity policy's (spec 3.2 §7.2, §7.9). Defaults to none.
    pub quiet_hours: Option<QuietHours>,
    /// Every partition's quotas: max running, max queued, the daily spend cap (spec 3.2
    /// §7.9). Defaults to none.
    pub quotas: Quotas,
    /// Spreads the kernel's cron ticks and schedule fires: each is delayed by a share of the
    /// gap to the next one, under half of it, the share derived from the source or schedule
    /// and the [`app_name`](Self::app_name). The tick keeps its scheduled time as its key and
    /// watermark. Defaults to none.
    pub cron_jitter: Option<Jitter>,
}

impl Default for KernelConfig {
    fn default() -> Self {
        Self {
            app_name: "adk-rust".to_string(),
            home: dirs::config_dir().unwrap_or_else(|| PathBuf::from(".")).join("adk-rust"),
            queues: QueueClass::defaults(),
            worker: DurableWorkerConfig::default(),
            scheduler_tick: Duration::from_secs(1),
            governance: GovernanceControl::new(),
            control: ControlPlaneConfig::default().without_socket(),
            fail_if_sandbox_unavailable: false,
            clock: Arc::new(SystemClock),
            proactivity: ProactivityPolicy::default(),
            quiet_hours: None,
            quotas: Quotas::default(),
            cron_jitter: None,
        }
    }
}

impl KernelConfig {
    /// Sets the proactivity limits (spec 3.2 §7.5).
    #[must_use]
    pub fn with_proactivity(mut self, proactivity: ProactivityPolicy) -> Self {
        self.proactivity = proactivity;
        self
    }

    /// Sets the kernel's quiet hours (spec 3.2 §7.2, §7.9).
    #[must_use]
    pub fn with_quiet_hours(mut self, quiet_hours: QuietHours) -> Self {
        self.quiet_hours = Some(quiet_hours);
        self
    }

    /// Sets every partition's quotas (spec 3.2 §7.9).
    #[must_use]
    pub fn with_quotas(mut self, quotas: Quotas) -> Self {
        self.quotas = quotas;
        self
    }

    /// Delays each cron tick and schedule fire by `jitter` (see
    /// [`cron_jitter`](Self::cron_jitter)): the kernel's own cron sources, the cron wakes of
    /// sleepers, a managed tenant's cron sources and the schedule store's `DurableScheduler`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::time::Duration;
    /// use adk_core::schedule::Jitter;
    /// use adk_kernel::KernelConfig;
    ///
    /// let config = KernelConfig::default().with_cron_jitter(Jitter::new(15, Duration::from_secs(540)));
    /// assert_eq!(config.cron_jitter, Some(Jitter::default()));
    /// ```
    #[must_use]
    pub fn with_cron_jitter(mut self, jitter: Jitter) -> Self {
        self.cron_jitter = Some(jitter);
        self
    }

    /// [`cron_jitter`](Self::cron_jitter) salted with the application name, so two kernels
    /// or tenants whose sources share names spread apart.
    pub(crate) fn salted_cron_jitter(&self) -> Option<Jitter> {
        self.cron_jitter.map(|jitter| jitter.salted(&self.app_name))
    }

    /// The mirrored kill switch's poll interval on multi-replica (K-I8): no backend
    /// implements `GovernanceWatch`, so the default 2 s poll would miss the one-second bound.
    pub const GOVERNANCE_POLL: Duration = Duration::from_millis(250);

    /// How long [`Kernel::start`] waits for the first read of a mirrored kill switch before
    /// it takes work anyway, refusing it until the mirror reads the store.
    pub const GOVERNANCE_FIRST_READ: Duration = Duration::from_secs(5);

    /// Sets the application runs belong to.
    #[must_use]
    pub fn with_app_name(mut self, app_name: impl Into<String>) -> Self {
        self.app_name = app_name.into();
        self
    }

    /// Sets the kernel home.
    #[must_use]
    pub fn with_home(mut self, home: impl Into<PathBuf>) -> Self {
        self.home = home.into();
        self
    }

    /// Sets the queue classes.
    #[must_use]
    pub fn with_queues(mut self, queues: impl IntoIterator<Item = QueueClass>) -> Self {
        self.queues = queues.into_iter().collect();
        self
    }

    /// Sets the worker configuration every queue's worker starts from.
    #[must_use]
    pub fn with_worker(mut self, worker: DurableWorkerConfig) -> Self {
        self.worker = worker;
        self
    }

    /// Sets how often the scheduler looks for due schedules.
    #[must_use]
    pub fn with_scheduler_tick(mut self, tick: Duration) -> Self {
        self.scheduler_tick = tick;
        self
    }

    /// Sets the kill switch.
    #[must_use]
    pub fn with_governance(mut self, governance: GovernanceControl) -> Self {
        self.governance = governance;
        self
    }

    /// Sets the control plane.
    #[must_use]
    pub fn with_control(mut self, control: ControlPlaneConfig) -> Self {
        self.control = control;
        self
    }

    /// Refuses to start a driver where no sandbox enforcer exists.
    #[must_use]
    pub fn with_fail_if_sandbox_unavailable(mut self, fail: bool) -> Self {
        self.fail_if_sandbox_unavailable = fail;
        self
    }

    /// Sets the clock the kernel reads, such as a `ManualClock` a test advances.
    #[must_use]
    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
        self.clock = clock;
        self
    }

    /// The configuration of the worker for `queue`: [`worker`](Self::worker) with the
    /// class's queue name, its poll interval (spec 3.2 §7.9, §13 Q2) and a worker id
    /// suffixed with the queue.
    pub fn worker_config(&self, queue: &QueueClass) -> DurableWorkerConfig {
        let worker_id = format!("{}:{}", self.worker.worker_id, queue.as_str());
        self.worker
            .clone()
            .with_worker_id(worker_id)
            .with_queue(queue.as_str())
            .with_poll_interval(queue.poll_interval())
    }

    /// A kill switch mirrored from `store` with the 250 ms poll K-I8 needs, for replicas
    /// that share one governance store.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::InMemoryGovernanceStateStore;
    /// use adk_kernel::KernelConfig;
    ///
    /// let control = KernelConfig::mirrored_governance(Arc::new(InMemoryGovernanceStateStore::new()));
    /// assert!(control.is_mirrored());
    /// ```
    pub fn mirrored_governance(store: Arc<dyn GovernanceStateStore>) -> GovernanceControl {
        GovernanceControl::mirrored(
            store,
            GovernanceMirrorConfig::default().with_poll_interval(Self::GOVERNANCE_POLL),
        )
    }
}

/// Where the kernel is in its lifecycle (spec 3.2 §7.2).
///
/// # Example
///
/// ```rust
/// use adk_kernel::KernelState;
///
/// assert_eq!(KernelState::Paused.to_string(), "paused");
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum KernelState {
    /// Built, not started.
    #[default]
    Built,
    /// Workers claim, the scheduler ticks, wake sources deliver.
    Running,
    /// Workers do not claim; running processes finish their attempt.
    Paused,
    /// Running processes are being suspended at their next checkpoint.
    Draining,
    /// Stopped; the control plane is closed.
    Stopped,
}

impl fmt::Display for KernelState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Built => "built",
            Self::Running => "running",
            Self::Paused => "paused",
            Self::Draining => "draining",
            Self::Stopped => "stopped",
        })
    }
}

/// The kernel's health (spec 3.2 §7.2): per worker, scheduler lag and store latency.
///
/// Driver states join in phase 3.
///
/// # Example
///
/// ```rust
/// use adk_kernel::{KernelHealth, KernelState};
///
/// let health = KernelHealth::default();
/// assert_eq!(health.state, KernelState::Built);
/// assert_eq!(serde_json::to_value(&health).unwrap()["state"], "built");
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct KernelHealth {
    /// The lifecycle state.
    pub state: KernelState,
    /// Whether the kill switch is engaged.
    pub frozen: bool,
    /// One entry per queue's worker.
    #[serde(default)]
    pub workers: Vec<WorkerHealth>,
    /// How far the scheduler's last tick ran behind its due time.
    #[serde(
        default,
        rename = "schedulerLagMs",
        skip_serializing_if = "Option::is_none",
        with = "crate::serde_util::option_millis"
    )]
    pub scheduler_lag: Option<Duration>,
    /// The run store's latest round-trip time.
    #[serde(
        default,
        rename = "storeLatencyMs",
        skip_serializing_if = "Option::is_none",
        with = "crate::serde_util::option_millis"
    )]
    pub store_latency: Option<Duration>,
}

/// The runner's code for a run that has not built its context yet, whose plugins cannot
/// screen a steering message.
const STEER_RUN_NOT_READY_CODE: &str = "agent.steer.run_not_ready";

/// A message a running process holds for its agent's next safe point (spec 3.3 §6 "steer"):
/// what [`Kernel::steer`] answers.
///
/// The message is delivered when the session holds an event whose steering marker carries
/// the receipt's steer id; it is handed back when the claim ends without one.
#[derive(Debug)]
#[non_exhaustive]
pub struct Steering {
    /// The process that holds the message.
    pub pid: String,
    /// The lease epoch of the claim that holds it; a later claim of the process never
    /// delivers it.
    pub lease_epoch: u64,
    /// Resolves once the turn takes the message, or ends first and hands it back.
    pub receipt: adk_core::SteerReceipt,
}

/// What [`Kernel::run_now`] runs now.
///
/// # Example
///
/// ```rust
/// use adk_kernel::RunNowTarget;
///
/// let target = RunNowTarget::Trigger { name: "nightly".into() };
/// assert_eq!(serde_json::to_value(&target).unwrap(), serde_json::json!({"trigger": {"name": "nightly"}}));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
#[non_exhaustive]
pub enum RunNowTarget {
    /// A process asleep on a cron wake, such as one `adk-rust wake --cron` started.
    Process {
        /// The process id.
        pid: String,
    },
    /// A standing trigger on a cron wake.
    Trigger {
        /// The trigger's name.
        name: String,
    },
}

/// What [`Kernel::run_now`] queued.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RunNow {
    /// The wake's key, [`keys::run_now`].
    pub key: String,
    /// The `kernel.wake` run that routes it.
    pub wake_run_id: String,
    /// `true` when an earlier request with the same id queued it.
    pub existing: bool,
}

/// One worker's health (spec 3.2 §7.2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct WorkerHealth {
    /// The queue class it claims.
    pub queue: QueueClass,
    /// The lease owner name it writes.
    pub worker_id: String,
    /// Whether its claim loop is running.
    pub claiming: bool,
    /// Runs it executes now.
    pub active_runs: usize,
}

impl WorkerHealth {
    /// A worker of `queue` named `worker_id`, not claiming, with no active runs.
    pub fn new(queue: QueueClass, worker_id: impl Into<String>) -> Self {
        Self { queue, worker_id: worker_id.into(), claiming: false, active_runs: 0 }
    }
}

/// The resident supervisor (spec 3.2 §7.2). Cloning shares the kernel.
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use adk_core::InMemoryRunStore;
/// use adk_kernel::{Kernel, KernelConfig};
///
/// # async fn example(runner: Arc<adk_runner::Runner>) -> adk_kernel::Result<()> {
/// let kernel = Kernel::builder()
///     .config(KernelConfig::default())
///     .run_store(Arc::new(InMemoryRunStore::new()))
///     .agent("adk-rust", runner)
///     .build()?;
/// kernel.start().await?;
/// kernel.shutdown_on_signal().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Kernel {
    inner: Arc<KernelInner>,
}

pub(crate) struct KernelInner {
    config: KernelConfig,
    sup: Arc<Supervision>,
    processes: ProcessTable,
    agenda: Agenda,
    partitions: Partitions,
    router: WakeRouter,
    schedules: Option<Arc<dyn ScheduleStore>>,
    /// Where each stateful store came from (spec 3.2 §7.1).
    store_uses: Vec<StoreUse>,
    approvals: Option<Arc<dyn ApprovalService>>,
    sessions: Option<Arc<dyn SessionService>>,
    agents: BTreeMap<String, Arc<Runner>>,
    /// The agents a person adds (spec 3.3 §5.7, §10 K7).
    agent_table: crate::agents::Agents,
    workflows: Option<Arc<dyn WorkflowExecutor>>,
    wake_sources: Vec<Arc<dyn WakeSource>>,
    queue_ingresses: Vec<QueueIngress>,
    /// Whether the agent table can add agents: the builder was given a factory.
    adds_agents: bool,
    /// The signal store of each partition the kernel files signals in (spec 3.5 §7.10).
    #[cfg(feature = "charter")]
    signal_stores: BTreeMap<PartitionId, Arc<dyn crate::charter::SignalStore>>,
    /// Warnings the host or a kit added to the inventory.
    inventory_warnings: Vec<InventoryWarning>,
    consolidation: Option<ConsolidationTicker>,
    #[cfg(feature = "drivers")]
    drivers: Option<crate::drivers::DriverSupervisor>,
    runtime: tokio::sync::Mutex<Runtime>,
    status: Arc<RwLock<Status>>,
    #[cfg(feature = "proc")]
    ledger: Option<Ledger>,
    /// The background sub-agent host ([`KernelBuilder::subagents`]).
    subagents: Option<DurableSubagents>,
    /// [`control::router`](crate::control::router) built the control plane's routes for a
    /// server ([`Kernel::serves_routes`]).
    serves_routes: std::sync::atomic::AtomicBool,
}

/// What a started kernel runs besides its claim loops.
#[derive(Default)]
struct Runtime {
    stop: Option<CancellationToken>,
    tasks: Vec<JoinHandle<()>>,
    control: Option<ControlPlane>,
    /// Claim loops a pause shut down, finishing their attempts.
    stopping: Vec<JoinHandle<()>>,
    /// The kernel is paused by a drain, whose attempts are parked or abandoned, so `stop`
    /// has nothing left to drain.
    drained: bool,
}

/// The health the loops measure, read by [`Kernel::health`].
#[derive(Debug, Clone, Default)]
struct Status {
    state: KernelState,
    scheduler_lag: Option<Duration>,
    store_latency: Option<Duration>,
    active: HashMap<String, usize>,
}

impl fmt::Debug for Kernel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Kernel")
            .field("app_name", &self.inner.config.app_name)
            .field("home", &self.inner.config.home)
            .field("queues", &self.inner.config.queues)
            .field("state", &self.state())
            .finish_non_exhaustive()
    }
}

impl Kernel {
    /// How long [`shutdown_on_signal`](Self::shutdown_on_signal) drains before it stops.
    pub const SIGTERM_DRAIN: Duration = Duration::from_secs(30);

    /// A builder.
    pub fn builder() -> KernelBuilder {
        KernelBuilder::new()
    }

    /// The configuration the kernel was built with.
    pub fn config(&self) -> &KernelConfig {
        &self.inner.config
    }

    /// Each stateful store of the kernel: where it came from and whether it is known to be
    /// held in memory (spec 3.2 §7.1, [`KernelBuilder::require_durable`]).
    pub fn store_uses(&self) -> &[StoreUse] {
        &self.inner.store_uses
    }

    /// What the kernel runs, and a warning for each thing it would silently not do
    /// ([`KernelInventory`]): logged when the kernel starts and served at
    /// `GET /api/kernel/inventory`.
    pub fn inventory(&self) -> KernelInventory {
        let inner = &self.inner;
        let mut warnings = Vec::new();
        #[cfg(feature = "charter")]
        let signal_partitions: Vec<PartitionId> = inner.signal_stores.keys().cloned().collect();
        #[cfg(not(feature = "charter"))]
        let signal_partitions: Vec<PartitionId> = Vec::new();
        let triggers: Vec<InventoryTrigger> = inner
            .router
            .triggers()
            .iter()
            .map(|trigger| {
                let served = self.has_target(&trigger.run.target);
                if !served {
                    warnings.push(
                        InventoryWarning::new(
                            InventoryWarning::TRIGGER_UNSERVED,
                            format!(
                                "trigger `{}` starts `{}`, which no agent or workflow of the \
                                 kernel serves, so each of its runs fails; register the target \
                                 or remove the trigger",
                                trigger.name, trigger.run.target
                            ),
                        )
                        .with_subject(trigger.name.clone()),
                    );
                }
                if let Wake::Signal { kind, partition } = &trigger.wake {
                    let filed = match partition {
                        Some(partition) => signal_partitions.contains(partition),
                        None => !signal_partitions.is_empty(),
                    };
                    if !filed {
                        let place = partition
                            .as_ref()
                            .map_or_else(|| "any partition".to_string(), |p| format!("`{p}`"));
                        warnings.push(
                            InventoryWarning::new(
                                InventoryWarning::SIGNAL_UNFILED,
                                format!(
                                    "trigger `{}` wakes on `{kind}` signals in {place}, and the \
                                     kernel files no signals there, so it never fires; register \
                                     a signal store with KernelBuilder::signals",
                                    trigger.name
                                ),
                            )
                            .with_subject(trigger.name.clone()),
                        );
                    }
                }
                InventoryTrigger {
                    name: trigger.name.clone(),
                    wake: trigger.wake.clone(),
                    target: trigger.run.target.clone(),
                    queue: trigger.run.queue.clone(),
                    partition: trigger.partition.clone(),
                    overlap: trigger.overlap,
                    served,
                }
            })
            .collect();
        let served = inner.config.control.socket.is_some() || inner.config.control.http.is_some();
        let mut bundled: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
        for used in inner.store_uses.iter().filter(|used| used.in_memory) {
            match (used.origin, &used.bundle) {
                (StoreOrigin::Bundle, Some(label)) => {
                    bundled.entry(label.as_str()).or_default().push(used.store.as_str());
                }
                // The settings store is read only by a control plane.
                (StoreOrigin::Defaulted, _) if used.store == "control_store" && !served => {}
                _ => warnings.push(
                    InventoryWarning::new(
                        InventoryWarning::STORE_IN_MEMORY,
                        format!(
                            "the kernel keeps its `{}` in memory, so its state ends with the \
                             process; give the builder durable stores (KernelBuilder::stores) or \
                             set it with {}",
                            used.store,
                            store_remedy(&used.store)
                        ),
                    )
                    .with_subject(used.store.clone()),
                ),
            }
        }
        for (label, stores) in bundled {
            warnings.push(
                InventoryWarning::new(
                    InventoryWarning::STORE_IN_MEMORY,
                    format!(
                        "the stores `{label}` keep {} in memory, so their state ends with the \
                         process",
                        stores.join(", ")
                    ),
                )
                .with_subject(label),
            );
        }
        let targets = self.targets();
        if targets.is_empty()
            && triggers.is_empty()
            && inner.schedules.is_none()
            && inner.workflows.is_none()
            && !inner.adds_agents
        {
            warnings.push(InventoryWarning::new(
                InventoryWarning::KERNEL_IDLE,
                "the kernel has nothing to run: no agent, trigger, workflow, schedule store or \
                 agent factory",
            ));
        }
        warnings.extend(inner.inventory_warnings.iter().cloned());
        KernelInventory {
            app_name: inner.config.app_name.clone(),
            targets,
            triggers,
            wake_sources: inner
                .wake_sources
                .iter()
                .map(|source| source.name().to_string())
                .collect(),
            schedules: inner.schedules.is_some(),
            signal_partitions,
            stores: inner.store_uses.clone(),
            warnings,
        }
    }

    /// The sink that files signals in `partition` (spec 3.5 §7.10; feature `charter`): on
    /// the kernel's agenda store, wake router, event bus, clock and audit trail, through the
    /// store [`KernelBuilder::signals`] registered for the partition. Each filed or counted
    /// signal wakes the [`Wake::Signal`] sleepers and triggers of the partition.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Config`] when no signal store is registered for `partition`.
    #[cfg(feature = "charter")]
    pub fn signal_sink(
        &self,
        partition: impl Into<PartitionId>,
    ) -> Result<crate::charter::SignalSink> {
        let partition = partition.into();
        let store =
            self.inner.signal_stores.get(&partition).ok_or_else(|| KernelError::Config {
                reason: format!(
                    "the kernel files no signals in partition `{partition}`; register a signal \
                 store for it with KernelBuilder::signals"
                ),
            })?;
        let sink = crate::charter::SignalSink::for_kernel(self, Arc::clone(store), partition);
        Ok(match &self.inner.sup.audit {
            Some(trail) => sink.with_audit(trail.clone()),
            None => sink,
        })
    }

    fn state(&self) -> KernelState {
        self.inner.status.read().unwrap_or_else(|e| e.into_inner()).state
    }

    fn set_state(&self, state: KernelState) {
        self.inner.status.write().unwrap_or_else(|e| e.into_inner()).state = state;
    }

    fn lifecycle_fields(&self, reason: Option<&str>) -> serde_json::Value {
        json!({
            "kernelId": self.inner.sup.kernel_id,
            "home": self.inner.config.home,
            "replicas": serde_json::Value::Null,
            "reason": reason,
        })
    }

    async fn record_lifecycle(&self, action: &str, reason: Option<&str>) {
        let sup = &self.inner.sup;
        sup.record(action, sup.actor_for(None), self.lifecycle_fields(reason)).await;
    }

    /// Starts a claim loop for every queue class.
    fn spawn_workers(&self) {
        let sup = &self.inner.sup;
        let mut handles = sup.handles.lock().unwrap_or_else(|e| e.into_inner());
        for (queue, worker) in sup.workers() {
            handles.push((queue.clone(), worker.clone().spawn()));
        }
    }

    /// Starts the workers, scheduler, wake sources and control plane, after reconciling
    /// the wakes missed while the kernel was down. Records `kernel.started`.
    ///
    /// A mirrored kill switch is read before anything else, for at most
    /// [`KernelConfig::GOVERNANCE_FIRST_READ`], so work spawned once `start` returns is
    /// decided by the store's state rather than refused as never read. A store that cannot be
    /// read in that time leaves the control stale: the kernel starts and refuses work until
    /// its mirror reads the store.
    ///
    /// Processes a drain parked are woken first, and those a freeze parked when the control
    /// allows work again.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Lifecycle`] when the kernel already runs,
    /// [`KernelError::ControlPlane`] when the socket or bind is taken, or a store error.
    pub async fn start(&self) -> Result<()> {
        let mut runtime = self.inner.runtime.lock().await;
        let state = self.state();
        if !matches!(state, KernelState::Built | KernelState::Stopped) {
            return Err(KernelError::Lifecycle { state, action: "start" });
        }
        let sup = Arc::clone(&self.inner.sup);
        let config = &self.inner.config;
        let governance = &config.governance;
        if let Some(trail) = &sup.audit
            && governance.audit().is_none()
        {
            governance.attach_audit(trail.clone());
        }
        let stop = CancellationToken::new();
        let mut tasks = Vec::new();
        // Until a mirrored control's first read, `check` refuses all work and `is_frozen`
        // reads a freeze in force as lifted.
        match tokio::time::timeout(KernelConfig::GOVERNANCE_FIRST_READ, governance.refresh()).await
        {
            Ok(Ok(())) => {}
            Ok(Err(error)) => tracing::warn!(
                error = %error,
                "could not read the governance store; work is refused until it is read"
            ),
            Err(_) => tracing::warn!(
                timeout.ms = KernelConfig::GOVERNANCE_FIRST_READ.as_millis() as u64,
                "the governance store did not answer; work is refused until it is read"
            ),
        }
        if let Some(mirror) = governance.spawn_mirror() {
            tasks.push(mirror);
        }
        sup.draining.store(false, Ordering::SeqCst);
        // Sleepers' cron occurrences missed while stopped are planned from the stored cursors.
        sup.crons.lock().unwrap_or_else(|e| e.into_inner()).clear();
        *sup.cron_started.lock().unwrap_or_else(|e| e.into_inner()) = None;
        for progress in sup.progress_sources() {
            progress.attach(ProcessHandle::new(&sup));
            #[cfg(feature = "proc")]
            if let Some(ledger) = &self.inner.ledger {
                progress.attach_ledger(Arc::new(ledger.clone()));
            }
        }
        for partition in sup.partition_progress.keys() {
            if matches!(sup.partitions.get(partition).await, Ok(None)) {
                tracing::warn!(
                    partition = %partition,
                    "a progress source is registered for a partition the partition table does not hold"
                );
            }
        }
        if governance.check().is_ok() {
            sup.wake_suspended(&Suspension::Freeze).await;
        }
        sup.wake_suspended(&Suspension::Drain).await;
        #[cfg(feature = "drivers")]
        if let Some(drivers) = &self.inner.drivers {
            drivers.attach(
                &sup.bus,
                sup.audit.as_ref(),
                &sup.kernel_id,
                &config.app_name,
                &config.home,
                config.fail_if_sandbox_unavailable,
            );
            if let Err(error) = drivers.start().await {
                tracing::warn!(error = %error, "could not load the mounted drivers");
            }
        }
        match self.inner.router.reconcile().await {
            Ok(outcomes) if !outcomes.is_empty() => {
                tracing::info!(
                    wakes = outcomes.len(),
                    "woke processes for changes missed while the kernel was down"
                );
            }
            Ok(_) => {}
            Err(error) => tracing::warn!(error = %error, "could not reconcile missed wakes"),
        }
        // Every active added agent is built before the first claim (spec 3.3 §5.7).
        if let Err(error) = self.inner.agent_table.reconcile().await {
            tracing::warn!(error = %error, "could not host the added agents yet; the next tick retries");
        }
        self.spawn_workers();
        if let Some(subagents) = self.inner.subagents.clone() {
            // A parent is told about a sub-agent that finished while no kernel ran.
            tasks.push(tokio::spawn(async move {
                match subagents.reconcile().await {
                    Ok(looked) => {
                        tracing::debug!(subagents.looked = looked, "sub-agent notices reconciled")
                    }
                    Err(error) => {
                        tracing::warn!(error = %error, "could not reconcile sub-agent notices")
                    }
                }
            }));
        }
        if let Some(schedules) = &self.inner.schedules {
            let mut scheduler = DurableScheduler::new(Arc::clone(schedules), Arc::clone(&sup.runs))
                .with_governance(governance.clone())
                .with_clock(Arc::clone(&config.clock));
            if let Some(jitter) = config.salted_cron_jitter() {
                scheduler = scheduler.with_jitter(jitter);
            }
            tasks.push(spawn_scheduler(
                scheduler,
                Arc::clone(&sup),
                config.scheduler_tick,
                Arc::clone(&self.inner.status),
                stop.clone(),
            ));
        }
        for source in &self.inner.wake_sources {
            tasks.push(spawn_wake_source(
                Arc::clone(source),
                Arc::clone(&sup),
                self.inner.router.clone(),
                stop.clone(),
            ));
        }
        for ingress in &self.inner.queue_ingresses {
            tasks.push(spawn_queue_ingress(ingress.clone(), Arc::clone(&sup), stop.clone()));
        }
        if let Some(approvals) = &self.inner.approvals {
            // Inbox requests expire by the kernel's clock, as its agenda items and wakes do:
            // an item's request carries the item's expiry.
            let approvals = Arc::clone(approvals);
            let clock = Arc::clone(&config.clock);
            let every = config.scheduler_tick;
            tasks.push(tokio::spawn(async move {
                let mut timer = tokio::time::interval(every);
                timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
                loop {
                    timer.tick().await;
                    match approvals.tick(clock.now()).await {
                        Ok(report) if report.expired.is_empty() && report.escalated.is_empty() => {}
                        Ok(report) => tracing::info!(
                            approvals.expired = report.expired.len(),
                            approvals.escalated = report.escalated.len(),
                            "approval tick"
                        ),
                        Err(error) => tracing::warn!(error = %error, "approval tick failed"),
                    }
                }
            }));
        }
        tasks.push(spawn_mirror(Arc::clone(&sup), stop.clone()));
        tasks.push(spawn_file_watch(
            Arc::clone(&sup),
            self.inner.router.clone(),
            config.scheduler_tick,
            stop.clone(),
        ));
        tasks.push(spawn_maintenance(
            Arc::clone(&sup),
            self.inner.router.clone(),
            Ticks {
                agenda: self.inner.agenda.clone(),
                agents: self.inner.agent_table.clone(),
                consolidation: self.inner.consolidation.clone(),
            },
            Arc::clone(&self.inner.status),
            config.scheduler_tick,
            stop.clone(),
        ));
        if config.control.socket.is_some() || config.control.http.is_some() {
            match ControlPlane::start(self).await {
                Ok(plane) => runtime.control = Some(plane),
                Err(error) => {
                    stop.cancel();
                    for task in tasks {
                        task.abort();
                    }
                    let handles: Vec<_> =
                        sup.handles.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect();
                    for (_, handle) in handles {
                        handle.shutdown().await;
                    }
                    return Err(error);
                }
            }
        }
        runtime.stop = Some(stop);
        runtime.tasks = tasks;
        drop(runtime);
        self.set_state(KernelState::Running);
        self.record_lifecycle(audit::KERNEL_STARTED, None).await;
        sup.publish(KernelEvent::Health(self.health()));
        let inventory = self.inventory();
        tracing::info!(
            kernel.app = %inventory.app_name,
            kernel.targets = ?inventory.targets,
            kernel.triggers = inventory.triggers.len(),
            kernel.wake_sources = inventory.wake_sources.len(),
            kernel.schedules = inventory.schedules,
            kernel.warnings = inventory.warnings.len(),
            "kernel started"
        );
        for warning in &inventory.warnings {
            tracing::warn!(
                kernel.warning = %warning.code,
                kernel.subject = warning.subject.as_deref().unwrap_or_default(),
                "{}",
                warning.message
            );
        }
        Ok(())
    }

    /// Stops claiming; running processes run their attempt to its end. Records
    /// `kernel.paused`.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Lifecycle`] when the kernel is not running.
    pub async fn pause(&self) -> Result<()> {
        let mut runtime = self.inner.runtime.lock().await;
        let state = self.state();
        if state != KernelState::Running {
            return Err(KernelError::Lifecycle { state, action: "pause" });
        }
        let handles: Vec<_> =
            self.inner.sup.handles.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect();
        for (_, handle) in handles {
            runtime.stopping.push(tokio::spawn(handle.shutdown()));
        }
        drop(runtime);
        self.set_state(KernelState::Paused);
        self.record_lifecycle(audit::KERNEL_PAUSED, None).await;
        Ok(())
    }

    /// Claims again after [`pause`](Self::pause) or [`drain`](Self::drain), waking the
    /// processes a drain parked. Records `kernel.resumed`.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Lifecycle`] when the kernel is not paused.
    pub async fn resume(&self) -> Result<()> {
        let mut runtime = self.inner.runtime.lock().await;
        let state = self.state();
        if state != KernelState::Paused {
            return Err(KernelError::Lifecycle { state, action: "resume" });
        }
        self.spawn_workers();
        self.inner.sup.wake_suspended(&Suspension::Drain).await;
        runtime.drained = false;
        self.set_state(KernelState::Running);
        self.record_lifecycle(audit::KERNEL_RESUMED, None).await;
        Ok(())
    }

    /// Suspends running processes at their next checkpoint through S1's suspend path
    /// ([`Suspension::Drain`]), then stops claiming; on
    /// `timeout` aborts the claim loops so their leases lapse. Records `kernel.drained`.
    /// The kernel is paused afterwards: [`resume`](Self::resume) or a later
    /// [`start`](Self::start) wakes what the drain parked.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Lifecycle`] when the kernel is not running or paused, or a
    /// store error.
    pub async fn drain(&self, timeout: Duration) -> Result<()> {
        let mut runtime = self.inner.runtime.lock().await;
        let state = self.state();
        if !matches!(state, KernelState::Running | KernelState::Paused) {
            return Err(KernelError::Lifecycle { state, action: "drain" });
        }
        self.set_state(KernelState::Draining);
        let sup = &self.inner.sup;
        sup.draining.store(true, Ordering::SeqCst);
        let ours = sup.local_worker_ids();
        let deadline = tokio::time::Instant::now() + timeout;
        let mut busy;
        loop {
            busy = 0;
            for run in sup.running().await {
                if run.lease_owner.as_ref().is_some_and(|owner| ours.contains(owner)) {
                    busy += 1;
                    sup.suspend_local(&run.run_id);
                }
            }
            if busy == 0 || tokio::time::Instant::now() >= deadline {
                break;
            }
            tokio::time::sleep(DRAIN_POLL).await;
        }
        let handles: Vec<_> =
            sup.handles.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect();
        if busy == 0 {
            for (_, handle) in handles {
                handle.shutdown().await;
            }
        } else {
            tracing::warn!(
                runs = busy,
                "drain timed out; dropping the attempts still running so their leases lapse"
            );
            for (_, handle) in &handles {
                handle.abort();
            }
        }
        for stopping in runtime.stopping.drain(..) {
            if busy == 0 {
                let _ = stopping.await;
            } else {
                stopping.abort();
            }
        }
        runtime.drained = true;
        drop(runtime);
        sup.draining.store(false, Ordering::SeqCst);
        self.set_state(KernelState::Paused);
        let reason = (busy > 0).then_some("timeout");
        self.record_lifecycle(audit::KERNEL_DRAINED, reason).await;
        Ok(())
    }

    /// Drains for [`SIGTERM_DRAIN`](Self::SIGTERM_DRAIN), unless a [`drain`](Self::drain)
    /// already paused the kernel, stops drivers and closes the control plane. Records
    /// `kernel.stopped`.
    ///
    /// # Errors
    ///
    /// Returns a store or control-plane error; the kernel is stopped regardless.
    pub async fn stop(&self) -> Result<()> {
        let mut first_error = None;
        let drained = self.inner.runtime.lock().await.drained;
        let drains = match self.state() {
            KernelState::Running => true,
            KernelState::Paused => !drained,
            KernelState::Built | KernelState::Draining | KernelState::Stopped => false,
        };
        if drains && let Err(error) = self.drain(Self::SIGTERM_DRAIN).await {
            first_error = Some(error);
        }
        let mut runtime = self.inner.runtime.lock().await;
        if let Some(stop) = runtime.stop.take() {
            stop.cancel();
        }
        for task in runtime.tasks.drain(..) {
            task.abort();
        }
        for task in runtime.stopping.drain(..) {
            task.abort();
        }
        let watched: Vec<_> =
            std::mem::take(&mut *self.inner.sup.watched.lock().unwrap_or_else(|e| e.into_inner()))
                .into_values()
                .collect();
        for task in watched {
            task.abort();
        }
        let handles: Vec<_> =
            self.inner.sup.handles.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect();
        for (_, handle) in &handles {
            handle.abort();
        }
        if let Some(plane) = runtime.control.take()
            && let Err(error) = plane.shutdown().await
        {
            first_error.get_or_insert(error);
        }
        #[cfg(feature = "drivers")]
        if let Some(drivers) = &self.inner.drivers {
            drivers.shutdown().await;
        }
        // The agents a person added close with the kernel (spec 3.3 §5.7).
        self.inner.agent_table.close_hosted().await;
        runtime.drained = false;
        drop(runtime);
        let was = self.state();
        self.set_state(KernelState::Stopped);
        if was != KernelState::Stopped && was != KernelState::Built {
            self.record_lifecycle(audit::KERNEL_STOPPED, None).await;
        }
        first_error.map_or(Ok(()), Err)
    }

    /// Waits for `SIGTERM` or Ctrl-C — or, in a Windows service, the service manager's stop
    /// (spec 3.2 §10 W3) — then [`stop`](Self::stop)s, which drains once for
    /// [`SIGTERM_DRAIN`](Self::SIGTERM_DRAIN).
    ///
    /// # Errors
    ///
    /// Returns the error of `stop`, or [`KernelError::Io`] when the signal
    /// handler cannot be installed.
    pub async fn shutdown_on_signal(&self) -> Result<()> {
        #[cfg(unix)]
        {
            let mut terminate =
                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
            tokio::select! {
                result = tokio::signal::ctrl_c() => result?,
                _ = terminate.recv() => {}
            }
        }
        #[cfg(all(not(unix), feature = "service"))]
        tokio::select! {
            result = tokio::signal::ctrl_c() => result?,
            () = crate::service::stop_requested() => {}
        }
        #[cfg(all(not(unix), not(feature = "service")))]
        tokio::signal::ctrl_c().await?;
        tracing::info!("shutdown signal received; draining the kernel");
        self.stop().await
    }

    /// Freezes execution as `by`: `GovernanceControl::freeze_recorded`, then the running
    /// processes park `Waiting` at their next checkpoint with
    /// [`Suspension::Freeze`], one `kernel.process.suspended`
    /// record each, on every replica within one second (K-I8). No process starts until
    /// [`unfreeze`](Self::unfreeze).
    ///
    /// # Errors
    ///
    /// Returns the control's error when the freeze cannot be recorded; this replica is
    /// frozen regardless.
    pub async fn freeze(&self, reason: &str, by: AuditActor) -> Result<()> {
        self.inner.config.governance.freeze_recorded(reason, by).await?;
        Ok(())
    }

    /// Lifts the freeze as `by`: `GovernanceControl::unfreeze_recorded`, then wakes exactly
    /// the processes the freeze parked, never a manual or preempted suspension (K-I21).
    ///
    /// # Errors
    ///
    /// Returns the control's error when the unfreeze cannot be recorded; execution stays
    /// frozen.
    pub async fn unfreeze(&self, by: AuditActor) -> Result<()> {
        self.inner.config.governance.unfreeze_recorded(by).await?;
        let sup = &self.inner.sup;
        for (_, worker) in sup.workers() {
            worker.wake_frozen().await;
        }
        sup.wake_suspended(&Suspension::Freeze).await;
        sup.nudge();
        Ok(())
    }

    /// Runs a cron sleeper or a standing cron trigger now, outside its schedule, for `by`.
    ///
    /// The run now is a wake like a tick's: an event keyed [`keys::run_now`] that becomes its
    /// `kernel.wake` run, so a retried request with the same `request_id` routes once, and the
    /// router wakes the sleeper, or fires the trigger, as a tick would. The woken run passes
    /// admission like any other: quiet hours defer it, a spent budget parks it, a quota holds
    /// it. The schedule is untouched: no watermark moves, the next tick fires as planned, and
    /// a recurring sleeper's successor sleeps on the same cron wake after the run. The turn
    /// is told it was run now: its wake reason's payload carries `run_now`, the expression
    /// and who asked. The call is recorded as `kernel.run_now`.
    ///
    /// A run now of a trigger follows the trigger's [`WakeOverlap`](crate::WakeOverlap) as a
    /// tick does: while a process the trigger started is unfinished, `skip` refuses it here,
    /// `queueOne` queues one behind it or joins the one already waiting, and `queue` queues
    /// behind it.
    ///
    /// | Target | Must be |
    /// |---|---|
    /// | [`RunNowTarget::Process`] | `Waiting`, not suspended, its wake set holding a cron wake |
    /// | [`RunNowTarget::Trigger`] | A standing trigger of this kernel on a cron wake |
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use adk_core::audit_log::AuditActor;
    /// use adk_kernel::{Kernel, RunNowTarget};
    ///
    /// # async fn example(kernel: Kernel) -> adk_kernel::Result<()> {
    /// let run_now = kernel
    ///     .run_now(RunNowTarget::Trigger { name: "nightly-digest".into() }, None, AuditActor::default())
    ///     .await?;
    /// println!("queued {}", run_now.key);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Frozen`] while the kill switch refuses work, so nothing is
    /// queued; [`KernelError::NotFound`] or [`KernelError::InvalidState`] for a process that
    /// is missing or not asleep on a cron wake; [`KernelError::Config`] for a name no cron
    /// trigger has; [`KernelError::InvalidState`], naming the unfinished process, for a
    /// trigger whose overlap is `skip`; or a store error.
    pub async fn run_now(
        &self,
        target: RunNowTarget,
        request_id: Option<&str>,
        by: AuditActor,
    ) -> Result<RunNow> {
        let governance = &self.inner.config.governance;
        if let Err(error) = governance.check() {
            return Err(KernelError::Frozen {
                reason: governance.reason().unwrap_or(error.message),
            });
        }
        let sup = &self.inner.sup;
        let (key_target, expression, mut payload) = match &target {
            RunNowTarget::Process { pid } => {
                let run = sup
                    .runs
                    .get(pid)
                    .await?
                    .ok_or_else(|| KernelError::NotFound { pid: pid.clone() })?;
                let meta = sup.processes.get(pid).await?;
                let cron =
                    meta.as_ref().filter(|meta| meta.suspended_by.is_none()).and_then(|meta| {
                        meta.wake.iter().flat_map(|wake| wake.any_of.iter()).find_map(|wake| {
                            match wake {
                                Wake::Cron { expr, .. } => Some(expr.clone()),
                                _ => None,
                            }
                        })
                    });
                let Some(expression) = cron.filter(|_| run.state == adk_core::RunState::Waiting)
                else {
                    return Err(KernelError::InvalidState {
                        pid: pid.clone(),
                        state: run.state,
                        action: "run now (it is not asleep on a cron wake; `adk-rust resume` \
                                 wakes any sleeper)",
                    });
                };
                (pid.clone(), expression, json!({ "pid": pid }))
            }
            RunNowTarget::Trigger { name } => {
                let expression = self.inner.router.triggers().iter().find_map(|trigger| {
                    match (&trigger.wake, trigger.name == *name) {
                        (Wake::Cron { expr, .. }, true) => Some(expr.clone()),
                        _ => None,
                    }
                });
                let Some(expression) = expression else {
                    return Err(KernelError::Config {
                        reason: format!(
                            "no standing trigger `{name}` on a cron wake; `adk-rust inventory` \
                             lists the kernel's triggers"
                        ),
                    });
                };
                // Under `skip`, a run now while the trigger's process is unfinished would start
                // nothing; say so now rather than queue a wake that does nothing.
                if let Some(blocking) = self.inner.router.skips_run_now(name).await? {
                    return Err(KernelError::InvalidState {
                        pid: blocking.run_id,
                        state: blocking.state,
                        action: "joined by a run now of its trigger, whose overlap is `skip` \
                                 (let it finish, or `adk-rust kill` it)",
                    });
                }
                (format!("trigger:{name}"), expression, json!({ "trigger": name }))
            }
        };
        let request_id =
            request_id.map_or_else(|| uuid::Uuid::new_v4().to_string(), str::to_string);
        let key = keys::run_now(&key_target, &request_id);
        if let serde_json::Value::Object(fields) = &mut payload {
            fields.insert("run_now".into(), json!(true));
            fields.insert("expression".into(), json!(expression));
            fields.insert("requested_by".into(), json!(by.on_behalf_of));
        }
        let event = WakeEvent::new(crate::wake::RUN_NOW_SOURCE, key.clone(), payload);
        let (wake_run_id, existing) =
            match self.inner.router.submit(&event, &self.inner.config.app_name).await? {
                Enqueued::Created(run) => (run.run_id, false),
                Enqueued::Existing(run) => (run.run_id, true),
                Enqueued::Rejected { blocking_run_id } => {
                    return Err(KernelError::Config {
                        reason: format!(
                            "the run now `{key}` was refused by run {blocking_run_id}'s \
                             concurrency key"
                        ),
                    });
                }
            };
        sup.nudge();
        sup.record(
            audit::RUN_NOW,
            by,
            json!({ "target": target, "key": key, "expression": expression, "wakeRun": wake_run_id, "existing": existing }),
        )
        .await;
        tracing::info!(run_now.key = %key, run_now.existing = existing, "run now queued");
        Ok(RunNow { key, wake_run_id, existing })
    }

    /// Sends `text` to the turn of `user_id`'s session `session_id` that this replica runs
    /// (spec 3.3 §6 "steer"): `Runner::steer` on the runner of the process's target, so the
    /// message is screened as a turn's own message is and the agent takes it at its next safe
    /// point.
    ///
    /// Returns `None` when no turn of the session takes messages here: none runs, another
    /// replica runs it, its target is a workflow, or its run has not reached its agent yet.
    /// Send the message as the session's next message then. An added agent's turn that
    /// started before the agent was changed finishes on the build it started on, which is no
    /// longer hosted, so it answers `None` too.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Frozen`] while everything is stopped, or the runner's error
    /// when `text` is blank or an input guardrail or plugin refuses the message.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use adk_core::SteerOutcome;
    ///
    /// # async fn example(kernel: adk_kernel::Kernel) -> adk_kernel::Result<()> {
    /// match kernel.steer("ana", "s-1", "use the staging database").await? {
    ///     Some(steering) => match steering.receipt.outcome().await? {
    ///         SteerOutcome::Delivered { event_id } => println!("delivered as {event_id}"),
    ///         SteerOutcome::Returned(_) => println!("send it as the next message"),
    ///     },
    ///     None => println!("no turn runs here: send it as the next message"),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn steer(
        &self,
        user_id: &str,
        session_id: &str,
        text: &str,
    ) -> Result<Option<Steering>> {
        let governance = &self.inner.config.governance;
        if governance.is_frozen() {
            return Err(KernelError::Frozen { reason: governance.reason().unwrap_or_default() });
        }
        let message = adk_core::Content::new("user").with_text(text);
        adk_core::validate_steering_message(&message)?;
        let sup = &self.inner.sup;
        // The newest claim of the session on this replica; the session is the one its worker
        // runs the claim in, `run-{pid}` for a process spawned without one.
        let claimed = {
            let local = sup.local.lock().unwrap_or_else(|e| e.into_inner());
            local
                .values()
                .filter(|claim| {
                    let run = &claim.run;
                    run.app_name == sup.app_name
                        && run.user_id == user_id
                        && crate::supervise::run_session(run) == session_id
                })
                .max_by_key(|claim| claim.claimed_at)
                .map(|claim| claim.run.clone())
        };
        let Some(run) = claimed else { return Ok(None) };
        let runner = match self.inner.agents.get(&run.target) {
            Some(runner) => Arc::clone(runner),
            None => match sup.targets.hosted(&run.target) {
                Some(added) => added.runner,
                None => return Ok(None),
            },
        };
        let identity = adk_core::AdkIdentity::new(
            adk_core::AppName::try_from(runner.app_name()).map_err(adk_core::AdkError::from)?,
            adk_core::UserId::try_from(user_id).map_err(adk_core::AdkError::from)?,
            adk_core::SessionId::try_from(session_id).map_err(adk_core::AdkError::from)?,
        );
        match runner.steer(&identity, message).await {
            Ok(receipt) => {
                Ok(Some(Steering { pid: run.run_id, lease_epoch: run.lease_epoch, receipt }))
            }
            // The claim has not started its run, or the run ended meanwhile.
            Err(error)
                if error.code == adk_core::STEER_NO_ACTIVE_RUN_CODE
                    || error.code == STEER_RUN_NOT_READY_CODE =>
            {
                Ok(None)
            }
            Err(error) => Err(error.into()),
        }
    }

    /// The process table.
    pub fn processes(&self) -> &ProcessTable {
        &self.inner.processes
    }

    /// The background sub-agent host, when the kernel was built with
    /// [`KernelBuilder::subagents`].
    pub fn subagents(&self) -> Option<&DurableSubagents> {
        self.inner.subagents.as_ref()
    }

    pub(crate) fn from_inner(inner: Arc<KernelInner>) -> Self {
        Self { inner }
    }

    /// The agenda (spec 3.2 §7.5).
    pub fn agenda(&self) -> &Agenda {
        &self.inner.agenda
    }

    /// The partition table and its crossings (spec 3.2 §7.8).
    pub fn partitions(&self) -> &Partitions {
        &self.inner.partitions
    }

    /// The partition the target `target` is bound to, when it is a partition agent's.
    pub fn partition_of_target(&self, target: &str) -> Option<&PartitionId> {
        self.inner.sup.targets.statics().get(target)
    }

    /// The agents a person adds, by asking or by hand (spec 3.3 §5.7, §10 K7): every
    /// change to one goes through this table.
    pub fn agents(&self) -> &crate::agents::Agents {
        &self.inner.agent_table
    }

    /// The event bus.
    pub fn bus(&self) -> &EventBus {
        &self.inner.sup.bus
    }

    /// The wake matcher.
    pub fn wake_router(&self) -> &WakeRouter {
        &self.inner.router
    }

    /// The address the control plane's HTTP listener is bound to while the kernel runs, so
    /// a bind on port 0 is discoverable (spec 3.2 §7.11, spec 3.5 §8.2); `None` when the
    /// control plane serves no HTTP or the kernel is not running.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let control = ControlPlaneConfig::default().without_socket().with_http("127.0.0.1:0".parse()?);
    /// kernel.start().await?;
    /// let addr = kernel.control_addr().await.expect("the control plane listens");
    /// ```
    pub async fn control_addr(&self) -> Option<std::net::SocketAddr> {
        self.inner.runtime.lock().await.control.as_ref().and_then(ControlPlane::http_addr)
    }

    /// The content-free activity ledger the kernel writes, when it was built with one
    /// (spec 3.2 §7.10, feature `proc`).
    #[cfg(feature = "proc")]
    pub fn ledger(&self) -> Option<&Ledger> {
        self.inner.ledger.as_ref()
    }

    /// Whether [`control::router`](crate::control::router) built this kernel's control-plane
    /// routes for a server, so a page served beside them may read them: the web home reads
    /// `/api/kernel` only then (spec 3.3 §10).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # fn example(kernel: adk_kernel::Kernel) {
    /// assert!(!kernel.serves_routes());
    /// let _routes = adk_kernel::control::router(kernel.clone());
    /// assert!(kernel.serves_routes());
    /// # }
    /// ```
    pub fn serves_routes(&self) -> bool {
        self.inner.serves_routes.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Records that the control plane's routes were built for a server.
    pub(crate) fn mark_routes_served(&self) {
        self.inner.serves_routes.store(true, std::sync::atomic::Ordering::Relaxed);
    }

    /// What every kernel part shares, for the routes the surfaces need (spec 3.3 §10 K3,
    /// K4).
    pub(crate) fn supervision(&self) -> &Arc<Supervision> {
        &self.inner.sup
    }

    /// The end of the quiet time that holds `at` in `partition`, followed through windows
    /// that touch; `None` when `at` is not quiet (spec 3.3 §5.4, §10 K3). It reads the
    /// windows in force now: the kernel's, the proactivity policy's and the partition's own,
    /// with a quiet time the person changed while the kernel runs in place of the kernel's and
    /// the partition's. A phone's wake-up waits for it.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # async fn example(kernel: adk_kernel::Kernel) {
    /// use adk_kernel::PartitionId;
    ///
    /// if let Some(until) = kernel.quiet_until(&PartitionId::default(), chrono::Utc::now()).await {
    ///     println!("quiet until {until}");
    /// }
    /// # }
    /// ```
    pub async fn quiet_until(
        &self,
        partition: &PartitionId,
        at: chrono::DateTime<chrono::Utc>,
    ) -> Option<chrono::DateTime<chrono::Utc>> {
        let windows = self.inner.sup.quiet_windows(partition).await;
        let mut until = at;
        // Two windows release into each other at most once each.
        for _ in 0..=windows.len() {
            match windows
                .iter()
                .filter(|quiet| quiet.contains(until))
                .map(|quiet| quiet.release_at(until))
                .max()
            {
                Some(next) if next > until => until = next,
                _ => break,
            }
        }
        (until > at).then_some(until)
    }

    /// Subscribes to the event bus from now on.
    pub fn events(&self) -> EventSubscriber {
        self.inner.sup.bus.subscribe()
    }

    /// The kernel's health: per worker, scheduler lag, store latency.
    pub fn health(&self) -> KernelHealth {
        let status = self.inner.status.read().unwrap_or_else(|e| e.into_inner()).clone();
        let sup = &self.inner.sup;
        let claiming: Vec<QueueClass> = sup
            .handles
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .filter(|(_, handle)| !handle.is_finished())
            .map(|(queue, _)| queue.clone())
            .collect();
        let workers = sup
            .workers()
            .iter()
            .map(|(queue, worker)| {
                let worker_id = worker.config().worker_id.clone();
                let mut health = WorkerHealth::new(queue.clone(), worker_id.clone());
                health.claiming = claiming.contains(queue);
                health.active_runs = status.active.get(&worker_id).copied().unwrap_or(0);
                health
            })
            .collect();
        KernelHealth {
            state: status.state,
            frozen: self.inner.config.governance.is_frozen(),
            workers,
            scheduler_lag: status.scheduler_lag,
            store_latency: status.store_latency,
        }
    }
}

impl Kernel {
    /// The session service `attach` reads transcripts and holds from (spec 3.2 §7.11).
    pub(crate) fn session_service(&self) -> Option<&Arc<dyn SessionService>> {
        self.inner.sessions.as_ref()
    }

    /// The approval service the socket serves the `/api/approvals` inbox from (K5).
    pub(crate) fn approval_service(&self) -> Option<&Arc<dyn ApprovalService>> {
        self.inner.approvals.as_ref()
    }

    /// The audit trail `kernel.control` records go to (K-I16, spec 3.2 §9.3).
    pub(crate) fn audit_trail(&self) -> Option<&AuditTrail> {
        self.inner.sup.audit.as_ref()
    }

    /// The registered agent target names, sorted; workflow ids cannot be listed
    /// (spec 3.2 §7.11, `POST /api/kernel/processes`).
    pub(crate) fn targets(&self) -> Vec<String> {
        let mut targets: std::collections::BTreeSet<String> =
            self.inner.agents.keys().cloned().collect();
        targets.extend(self.inner.sup.targets.table.targets());
        targets.into_iter().collect()
    }

    /// The driver supervisor, when the kernel was built with one (spec 3.2 §7.7).
    #[cfg(feature = "drivers")]
    pub fn drivers(&self) -> Option<&crate::drivers::DriverSupervisor> {
        self.inner.drivers.as_ref()
    }

    /// Whether `target` is a registered agent target or a workflow the executor has.
    pub(crate) fn has_target(&self, target: &str) -> bool {
        let table = &self.inner.sup.targets.table;
        self.inner.agents.contains_key(target)
            || table.contains(target)
            || table.is_expected(target)
            || self.inner.workflows.as_ref().is_some_and(|workflows| workflows.has_workflow(target))
    }
}

#[async_trait]
impl FreezeDelegate for Kernel {
    async fn freeze(&self, reason: &str, by: AuditActor) -> adk_core::Result<FreezeReport> {
        // The running processes park at their next model-call boundary.
        let parked_runs = self.inner.sup.running().await.len();
        Kernel::freeze(self, reason, by).await?;
        Ok(FreezeReport { parked_runs, cancelled_runs: 0 })
    }

    async fn unfreeze(&self, by: AuditActor) -> adk_core::Result<()> {
        Kernel::unfreeze(self, by).await.map_err(Into::into)
    }
}

/// How long a queue ingress waits for a message before it pulls again.
const INGRESS_IDLE: Duration = Duration::from_secs(1);
/// How often a drain checks whether the suspended processes have parked.
const DRAIN_POLL: Duration = Duration::from_millis(50);

/// Ticks the scheduler every `tick`, recording how late each tick ran.
fn spawn_scheduler(
    scheduler: DurableScheduler,
    sup: Arc<Supervision>,
    tick: Duration,
    status: Arc<RwLock<Status>>,
    stop: CancellationToken,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        let mut due = tokio::time::Instant::now();
        loop {
            tokio::select! {
                () = stop.cancelled() => return,
                () = tokio::time::sleep_until(due) => {}
            }
            let lag = tokio::time::Instant::now().saturating_duration_since(due);
            match scheduler.tick().await {
                // A fired schedule runs now, not at its queue's next poll.
                Ok(fired) if fired.enqueued > 0 => sup.nudge(),
                Ok(_) => {}
                Err(error) => tracing::warn!(error = %error, "scheduler tick failed"),
            }
            status.write().unwrap_or_else(|e| e.into_inner()).scheduler_lag = Some(lag);
            due = (due + tick).max(tokio::time::Instant::now());
        }
    })
}

/// Runs `ingress` as `QueueIngress::run` does, waking the workers when a message became a
/// `kernel.wake` run, so a queue wake is claimed at once rather than at the maintenance
/// queue's next poll.
fn spawn_queue_ingress(
    ingress: QueueIngress,
    sup: Arc<Supervision>,
    stop: CancellationToken,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        loop {
            let pause = match ingress.poll_once().await {
                Ok(report) => {
                    if !report.created.is_empty() {
                        sup.nudge();
                    }
                    if report.pulled > 0 { Duration::ZERO } else { INGRESS_IDLE }
                }
                Err(error) => {
                    tracing::warn!(error = %error, "queue ingress pull failed");
                    INGRESS_IDLE
                }
            };
            tokio::select! {
                () = stop.cancelled() => return,
                () = tokio::time::sleep(pause) => {}
            }
        }
    })
}

/// Hands every event of `source` to [`WakeRouter::submit`], which enqueues a `kernel.wake`
/// run keyed by the event, until the kernel stops (spec 3.2 §7.4). The maintenance worker's
/// [`KernelWakeExecutor`] routes it, so a delivery is routed once however often it arrives
/// (K-I3) and survives a restart.
fn spawn_wake_source(
    source: Arc<dyn WakeSource>,
    sup: Arc<Supervision>,
    router: WakeRouter,
    stop: CancellationToken,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        let mut events = match source.subscribe().await {
            Ok(events) => events,
            Err(error) => {
                tracing::warn!(wake.source = source.name(), error = %error, "could not subscribe to a wake source");
                return;
            }
        };
        loop {
            let event = tokio::select! {
                () = stop.cancelled() => return,
                event = events.next() => event,
            };
            let Some(event) = event else { return };
            let key = event.key.clone();
            match router.submit(&event, &sup.app_name).await {
                Ok(Enqueued::Created(_)) => sup.nudge(),
                Ok(_) => {
                    tracing::debug!(wake.source = source.name(), wake.key = %key, "duplicate wake delivery");
                }
                Err(error) => {
                    tracing::warn!(wake.source = source.name(), wake.key = %key, error = %error, "could not hand a wake to the maintenance queue");
                }
            }
        }
    })
}

/// Keeps one file source per root a sleeper or trigger watches (spec 3.2 §7.4): a spawn
/// that names a new root signals at once, and every tick drops the roots no sleeper needs
/// any more. A source whose subscription failed is not retried until its root is dropped
/// and needed again.
fn spawn_file_watch(
    sup: Arc<Supervision>,
    router: WakeRouter,
    tick: Duration,
    stop: CancellationToken,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        loop {
            let roots = file_roots(&sup, &router).await;
            let mut started = Vec::new();
            {
                let mut watched = sup.watched.lock().unwrap_or_else(|e| e.into_inner());
                watched.retain(|root, task| {
                    let needed = roots.contains_key(root);
                    if !needed {
                        task.abort();
                        tracing::debug!(root = %root.display(), "no sleeper watches this root any more");
                    }
                    needed
                });
                for (root, debounce) in &roots {
                    if !watched.contains_key(root) {
                        started.push((root.clone(), *debounce));
                    }
                }
            }
            for (root, debounce) in started {
                let name = format!("file:{}", root.display());
                match FileWakeSource::new(name, root.clone(), "*") {
                    Ok(source) => {
                        let source: Arc<dyn WakeSource> = Arc::new(source.with_debounce(debounce));
                        let task = spawn_wake_source(
                            source,
                            Arc::clone(&sup),
                            router.clone(),
                            stop.clone(),
                        );
                        sup.watched.lock().unwrap_or_else(|e| e.into_inner()).insert(root, task);
                    }
                    Err(error) => {
                        tracing::warn!(root = %root.display(), error = %error, "could not watch a file wake's root");
                    }
                }
            }
            tokio::select! {
                () = stop.cancelled() => return,
                () = sup.roots_changed.notified() => {}
                () = tokio::time::sleep(tick) => {}
            }
        }
    })
}

/// The roots of the file wakes of every sleeper and trigger, each with the shortest
/// debounce asked for it.
async fn file_roots(sup: &Supervision, router: &WakeRouter) -> BTreeMap<PathBuf, Duration> {
    let mut roots: BTreeMap<PathBuf, Duration> = BTreeMap::new();
    let mut add = |wake: &Wake| {
        if let Wake::FileChange { root, debounce, .. } = wake {
            let root = std::fs::canonicalize(root).unwrap_or_else(|_| root.clone());
            let entry = roots.entry(root).or_insert(*debounce);
            *entry = (*entry).min(*debounce);
        }
    };
    for trigger in router.triggers() {
        add(&trigger.wake);
    }
    match sup.processes.list(&ProcessFilter::default()).await {
        Ok(metas) => {
            for wake in metas.iter().filter_map(|meta| meta.wake.as_ref()) {
                wake.any_of.iter().for_each(&mut add);
            }
        }
        Err(error) => tracing::debug!(error = %error, "could not list the sleepers' file wakes"),
    }
    roots
}

/// Every 250 ms (K-I8): suspends the running processes this replica leases that have a
/// pending request, and wakes the freeze-parked processes once the control allows work
/// again, publishing each change of the kill switch.
fn spawn_mirror(sup: Arc<Supervision>, stop: CancellationToken) -> JoinHandle<()> {
    tokio::spawn(async move {
        let mut frozen = sup.governance.is_frozen();
        let mut refused = sup.governance.check().is_err();
        loop {
            tokio::select! {
                () = stop.cancelled() => return,
                () = tokio::time::sleep(KernelConfig::GOVERNANCE_POLL) => {}
            }
            sup.mirror_suspend_requests().await;
            let now = sup.governance.is_frozen();
            if now != frozen {
                frozen = now;
                sup.publish(KernelEvent::Governance { frozen, reason: sup.governance.reason() });
            }
            // Work is allowed again after an unfreeze, and once a store that was stale, or not
            // read when the kernel started, is read unfrozen.
            let refuses = sup.governance.check().is_err();
            if refused && !refuses {
                for (_, worker) in sup.workers() {
                    worker.wake_frozen().await;
                }
                sup.wake_suspended(&Suspension::Freeze).await;
            }
            refused = refuses;
        }
    })
}

/// What the maintenance tick moves forward besides the supervision state: the agenda, the
/// agent table (spec 3.3 §5.7) and the consolidation tick.
struct Ticks {
    agenda: Agenda,
    agents: crate::agents::Agents,
    consolidation: Option<ConsolidationTicker>,
}

/// Every scheduler tick: expires wake sets and fires time wakes, claims wake runs enqueued
/// from outside the kernel, attributes spend, applies the agenda's decisions, makes the
/// daily review, runs the admission sweep (preempted processes whose preemptor finished,
/// processes waiting for a slot, budgets replenished), and measures the store.
fn spawn_maintenance(
    sup: Arc<Supervision>,
    router: WakeRouter,
    ticks: Ticks,
    status: Arc<RwLock<Status>>,
    tick: Duration,
    stop: CancellationToken,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        loop {
            tokio::select! {
                () = stop.cancelled() => return,
                () = tokio::time::sleep(tick) => {}
            }
            sup.fire_crons(&router).await;
            match router.sweep_expired(sup.clock.now()).await {
                Ok(outcomes) if !outcomes.is_empty() => sup.nudge(),
                Ok(_) => {}
                Err(error) => tracing::debug!(error = %error, "could not sweep expired wake sets"),
            }
            // A webhook ingress served outside the kernel, or another replica, enqueues
            // `kernel.wake` runs this kernel never sees enqueued: claim them within a tick
            // rather than at the maintenance queue's 5 s poll (§7.4, under 2 s).
            if sup.external_wakes_due().await {
                sup.nudge();
            }
            // The day that ended gets its baseline pass, once (spec 3.2 §7.10).
            #[cfg(feature = "proc-baselines")]
            if let Some(proc) = &sup.proc
                && proc.tick(&sup.runs, &sup.queues, sup.clock.now()).await
            {
                sup.nudge();
            }
            sup.attribute_all().await;
            ticks.agenda.tick().await;
            ticks.agents.tick().await;
            sup.review().await;
            if let Some(consolidation) = &ticks.consolidation {
                consolidation.tick().await;
            }
            // A preemptor that finished on another replica, a slot freed there, a new day.
            sup.requeue_preempted(None).await;
            if sup.caps_running().await {
                sup.admit_waiters().await;
            }
            let today = sup.clock.now().date_naive();
            for (partition, asleep) in sup.replenished_partitions().await {
                let event = crate::wake::WakeEvent::new(
                    "budget",
                    crate::wake::keys::budget(partition.as_str(), today, &asleep),
                    json!({ "partition": partition, "day": today }),
                );
                if let Err(error) = router.submit(&event, &sup.app_name).await {
                    tracing::debug!(partition = %partition, error = %error, "could not submit a budget wake");
                }
            }
            let probe = tokio::time::Instant::now();
            let running = sup.running().await;
            let latency = probe.elapsed();
            let mut active: HashMap<String, usize> = HashMap::new();
            for run in running {
                if let Some(owner) = run.lease_owner {
                    *active.entry(owner).or_default() += 1;
                }
            }
            let mut status = status.write().unwrap_or_else(|e| e.into_inner());
            status.store_latency = Some(latency);
            status.active = active;
        }
    })
}

/// The workflows every kernel worker runs: the kernel's `kernel.wake` and the caller's.
struct KernelWorkflows {
    user: Option<Arc<dyn WorkflowExecutor>>,
    wake: KernelWakeExecutor,
    /// The daily baseline pass, `kernel.proc` (spec 3.2 §7.10).
    #[cfg(feature = "proc-baselines")]
    proc: Option<Arc<crate::proc::baselines::ProcRuntime>>,
}

impl KernelWorkflows {
    /// The baseline pass when `workflow_id` names it.
    #[cfg(feature = "proc-baselines")]
    fn proc_for(&self, workflow_id: &str) -> Option<&Arc<crate::proc::baselines::ProcRuntime>> {
        self.proc.as_ref().filter(|_| workflow_id == crate::proc::baselines::PROC_TARGET)
    }
}

#[async_trait]
impl WorkflowExecutor for KernelWorkflows {
    fn has_workflow(&self, workflow_id: &str) -> bool {
        #[cfg(feature = "proc-baselines")]
        if self.proc_for(workflow_id).is_some() {
            return true;
        }
        self.wake.has_workflow(workflow_id)
            || self.user.as_ref().is_some_and(|user| user.has_workflow(workflow_id))
    }

    async fn execute(
        &self,
        workflow_id: &str,
        input: WorkflowState,
        cancel_token: CancellationToken,
    ) -> std::result::Result<serde_json::Value, String> {
        #[cfg(feature = "proc-baselines")]
        if let Some(proc) = self.proc_for(workflow_id) {
            let input = serde_json::Value::Object(input.into_iter().collect());
            return tokio::select! {
                done = proc.execute(input) => done,
                () = cancel_token.cancelled() => Err("the baseline pass was cancelled".to_string()),
            };
        }
        match &self.user {
            Some(user) if !self.wake.has_workflow(workflow_id) => {
                user.execute(workflow_id, input, cancel_token).await
            }
            _ => self.wake.execute(workflow_id, input, cancel_token).await,
        }
    }

    async fn execute_durable(
        &self,
        workflow_id: &str,
        input: WorkflowState,
        run: WorkflowRunContext,
    ) -> std::result::Result<serde_json::Value, String> {
        #[cfg(feature = "proc-baselines")]
        if self.proc_for(workflow_id).is_some() {
            return self.execute(workflow_id, input, run.cancel).await;
        }
        match &self.user {
            Some(user) if !self.wake.has_workflow(workflow_id) => {
                user.execute_durable(workflow_id, input, run).await
            }
            _ => self.wake.execute_durable(workflow_id, input, run).await,
        }
    }
}

/// The workflow executors a builder was given, each run going to the first that has its id.
struct WorkflowChain(Vec<Arc<dyn WorkflowExecutor>>);

impl WorkflowChain {
    fn find(&self, workflow_id: &str) -> std::result::Result<&Arc<dyn WorkflowExecutor>, String> {
        self.0
            .iter()
            .find(|executor| executor.has_workflow(workflow_id))
            .ok_or_else(|| format!("no workflow executor of the kernel has `{workflow_id}`"))
    }
}

#[async_trait]
impl WorkflowExecutor for WorkflowChain {
    fn has_workflow(&self, workflow_id: &str) -> bool {
        self.find(workflow_id).is_ok()
    }

    async fn execute(
        &self,
        workflow_id: &str,
        input: WorkflowState,
        cancel_token: CancellationToken,
    ) -> std::result::Result<serde_json::Value, String> {
        self.find(workflow_id)?.execute(workflow_id, input, cancel_token).await
    }

    async fn execute_durable(
        &self,
        workflow_id: &str,
        input: WorkflowState,
        run: WorkflowRunContext,
    ) -> std::result::Result<serde_json::Value, String> {
        self.find(workflow_id)?.execute_durable(workflow_id, input, run).await
    }
}

/// Emits a finished run's model calls, tool calls and tool durations as the OTel GenAI
/// histograms (spec 3.2 §7.10, §13 Q4).
#[cfg(feature = "proc")]
pub(crate) fn record_histograms(target: &str, counts: &crate::supervise::TranscriptCounts) {
    use opentelemetry::KeyValue;
    use std::sync::OnceLock;

    struct Instruments {
        inference_calls: opentelemetry::metrics::Histogram<u64>,
        tool_calls: opentelemetry::metrics::Histogram<u64>,
        tool_duration: opentelemetry::metrics::Histogram<f64>,
    }
    static INSTRUMENTS: OnceLock<Instruments> = OnceLock::new();
    let instruments = INSTRUMENTS.get_or_init(|| {
        let meter = opentelemetry::global::meter("adk-kernel");
        Instruments {
            inference_calls: meter
                .u64_histogram("gen_ai.invoke_agent.inference_calls")
                .with_description("Model calls per agent run")
                .build(),
            tool_calls: meter
                .u64_histogram("gen_ai.invoke_agent.tool_calls")
                .with_description("Tool calls per agent run")
                .build(),
            tool_duration: meter
                .f64_histogram("gen_ai.execute_tool.duration")
                .with_unit("s")
                .with_description("Tool call duration")
                .build(),
        }
    });
    let invoke = [
        KeyValue::new(adk_telemetry::semconv::GEN_AI_OPERATION_NAME, "invoke_agent"),
        KeyValue::new("gen_ai.agent.name", target.to_string()),
    ];
    instruments.inference_calls.record(counts.model_calls, &invoke);
    instruments.tool_calls.record(counts.tool_calls, &invoke);
    let execute = [KeyValue::new(adk_telemetry::semconv::GEN_AI_OPERATION_NAME, "execute_tool")];
    for seconds in &counts.tool_durations {
        instruments.tool_duration.record(*seconds, &execute);
    }
}

/// Builds a [`Kernel`] (spec 3.2 §7.2).
///
/// A run store is required; everything else is optional. The process store defaults to
/// [`InMemoryProcessStore`]. `Harness::kernel(..)` (feature `kernel` of `adk-harness`,
/// §10 HK1) returns one with the harness runner registered as the `adk-rust` and
/// `harness.goal` targets.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use adk_core::InMemoryRunStore;
/// use adk_kernel::{Kernel, KernelConfig};
///
/// let kernel = Kernel::builder()
///     .config(KernelConfig::default().with_app_name("ops"))
///     .run_store(Arc::new(InMemoryRunStore::new()))
///     .build()
///     .unwrap();
/// assert_eq!(kernel.config().app_name, "ops");
/// ```
#[derive(Default)]
pub struct KernelBuilder {
    config: KernelConfig,
    governance: Option<GovernanceControl>,
    runs: Option<Arc<dyn DurableRunStore>>,
    processes: Option<Arc<dyn ProcessStore>>,
    schedules: Option<Arc<dyn ScheduleStore>>,
    approvals: Option<Arc<dyn ApprovalService>>,
    sessions: Option<Arc<dyn SessionService>>,
    spend: Option<Arc<dyn SpendLedger>>,
    audit: Option<AuditTrail>,
    agents: BTreeMap<String, Arc<Runner>>,
    workflows: Vec<Arc<dyn WorkflowExecutor>>,
    #[cfg(feature = "charter")]
    kpi_trackers: Vec<crate::charter::KpiTracker>,
    wake_sources: Vec<Arc<dyn WakeSource>>,
    triggers: Vec<Trigger>,
    sinks: Vec<Arc<dyn EventSink>>,
    progress: Option<Arc<dyn ProgressSource>>,
    partition_progress: Vec<(PartitionId, Arc<dyn ProgressSource>)>,
    queue_ingresses: Vec<QueueIngress>,
    agenda: Option<Arc<dyn AgendaStore>>,
    agenda_handles: Vec<AgendaHandle>,
    agent_store: Option<Arc<dyn crate::agents::AgentStore>>,
    agent_factory: Option<Arc<dyn crate::agents::AgentFactory>>,
    agents_handles: Vec<crate::agents::AgentsHandle>,
    rule_source: Option<Arc<dyn crate::review::StandingRuleSource>>,
    consolidators: BTreeMap<PartitionId, Arc<dyn Consolidator>>,
    #[cfg(feature = "drivers")]
    drivers: Option<crate::drivers::DriverSupervisor>,
    audiences: BTreeMap<PartitionId, Arc<dyn ObservationAudience>>,
    #[cfg(feature = "proc")]
    ledger: Option<Ledger>,
    #[cfg(feature = "proc-baselines")]
    baselines: Option<crate::proc::baselines::BaselinePolicy>,
    #[cfg(feature = "proc-baselines")]
    phraser: Option<Arc<dyn crate::proc::baselines::ObservationPhraser>>,
    partitions: Option<Partitions>,
    partition_targets: BTreeMap<String, PartitionId>,
    watermarks: Option<Arc<dyn CronWatermarkStore>>,
    bundle: Option<KernelStores>,
    require_durable: bool,
    #[cfg(feature = "charter")]
    signal_stores: BTreeMap<PartitionId, Arc<dyn crate::charter::SignalStore>>,
    inventory_warnings: Vec<InventoryWarning>,
    subagents: Option<SubagentConfig>,
    subagent_handles: Vec<crate::subagents::SubagentHandle>,
}

impl fmt::Debug for KernelBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("KernelBuilder")
            .field("config", &self.config)
            .field("agents", &self.agents.keys().collect::<Vec<_>>())
            .field("triggers", &self.triggers.len())
            .field("wake_sources", &self.wake_sources.len())
            .finish_non_exhaustive()
    }
}

impl KernelBuilder {
    /// A builder with the default configuration and no stores.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the configuration.
    #[must_use]
    pub fn config(mut self, config: KernelConfig) -> Self {
        self.config = config;
        self
    }

    /// Sets the kill switch. It replaces [`KernelConfig::governance`] at
    /// [`build`](Self::build), whenever [`config`](Self::config) is called, so a builder
    /// from `Harness::kernel()` keeps the harness's control when the caller sets its own
    /// configuration.
    #[must_use]
    pub fn governance(mut self, control: GovernanceControl) -> Self {
        self.governance = Some(control);
        self
    }

    /// Sets the durable run store every process lives in. Required.
    #[must_use]
    pub fn run_store(mut self, runs: Arc<dyn DurableRunStore>) -> Self {
        self.runs = Some(runs);
        self
    }

    /// Sets the process side table. Defaults to [`InMemoryProcessStore`].
    #[must_use]
    pub fn process_store(mut self, processes: Arc<dyn ProcessStore>) -> Self {
        self.processes = Some(processes);
        self
    }

    /// Sets the schedule store the kernel's `DurableScheduler` fires.
    #[must_use]
    pub fn schedule_store(mut self, schedules: Arc<dyn ScheduleStore>) -> Self {
        self.schedules = Some(schedules);
        self
    }

    /// Sets the approval service, built with `StoreApprovalService::with_run_store` so a
    /// decision wakes the parked run; pass the same service to the agents' `RunConfig`.
    ///
    /// The kernel files every call the service would hold with no route into its inbox for
    /// the `operator` group, self-approval allowed, as `adk-rust up` routes them
    /// (`ApprovalService::route_unrouted`): a router the service was built with keeps
    /// deciding. It publishes `held` when a request is filed and `decided` when a decision
    /// resolves one (`ApprovalService::add_notifier`). A service that takes neither is named
    /// in [`Kernel::inventory`]. For [`Wake::Approval`] sleepers, build the service with
    /// `with_notifier(source)` over an [`ApprovalWakeSource`](crate::ApprovalWakeSource) and
    /// pass the same source to [`wake_source`](Self::wake_source).
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::{InMemoryApprovalStore, InMemoryRunStore, StoreApprovalService};
    /// use adk_kernel::Kernel;
    ///
    /// let runs = Arc::new(InMemoryRunStore::new());
    /// let approvals = Arc::new(
    ///     StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
    ///         .with_run_store(runs.clone()),
    /// );
    /// // The agents' runner takes the same service: `RunConfig::builder().approval_service(..)`.
    /// let kernel = Kernel::builder().run_store(runs).approval_service(approvals).build()?;
    /// assert!(!kernel.inventory().warnings.iter().any(|w| w.code.starts_with("kernel.approvals")));
    /// # Ok::<(), adk_kernel::KernelError>(())
    /// ```
    #[must_use]
    pub fn approval_service(mut self, approvals: Arc<dyn ApprovalService>) -> Self {
        self.approvals = Some(approvals);
        self
    }

    /// Sets the session service `attach` reads transcripts from.
    #[must_use]
    pub fn session_service(mut self, sessions: Arc<dyn SessionService>) -> Self {
        self.sessions = Some(sessions);
        self
    }

    /// Sets the spend ledger the process views read.
    #[must_use]
    pub fn spend_ledger(mut self, spend: Arc<dyn SpendLedger>) -> Self {
        self.spend = Some(spend);
        self
    }

    /// Sets the signed audit trail for the kernel's records (spec 3.2 §9.3).
    #[must_use]
    pub fn audit(mut self, trail: AuditTrail) -> Self {
        self.audit = Some(trail);
        self
    }

    /// Hosts `runner` as the target `target` on every queue's worker, as
    /// `DurableWorker::with_agent` does.
    #[must_use]
    pub fn agent(mut self, target: impl Into<String>, runner: Arc<Runner>) -> Self {
        self.agents.insert(target.into(), runner);
        self
    }

    /// Hosts workflow targets, as `DurableWorker::with_workflows` does, in place of every
    /// executor given before; [`workflow`](Self::workflow) adds one beside them.
    #[must_use]
    pub fn workflows(mut self, workflows: Arc<dyn WorkflowExecutor>) -> Self {
        self.workflows = vec![workflows];
        self
    }

    /// Adds `executor` beside the workflow executors given before: a workflow run goes to the
    /// first executor, in the order given, that has its workflow id. Products and kits each
    /// add their own, such as a site's workflows beside its KPI tracker.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::InMemoryRunStore;
    /// use adk_kernel::{Kernel, Trigger, Wake};
    /// use adk_server::background::{WorkflowExecutor, WorkflowState};
    /// use tokio_util::sync::CancellationToken;
    ///
    /// struct One(&'static str);
    ///
    /// #[async_trait::async_trait]
    /// impl WorkflowExecutor for One {
    ///     fn has_workflow(&self, id: &str) -> bool {
    ///         id == self.0
    ///     }
    ///
    ///     async fn execute(&self, _: &str, _: WorkflowState, _: CancellationToken) -> Result<serde_json::Value, String> {
    ///         Ok(serde_json::json!(self.0))
    ///     }
    /// }
    ///
    /// let run = |target: &str| adk_core::NewRun::new("background", "ops", "kernel", target, serde_json::json!({}));
    /// let kernel = Kernel::builder()
    ///     .run_store(Arc::new(InMemoryRunStore::new()))
    ///     .workflow(Arc::new(One("digest")))
    ///     .workflow(Arc::new(One("probe")))
    ///     .trigger(Trigger::new("weekly", Wake::Webhook { hook: "weekly".into() }, run("digest")))
    ///     .trigger(Trigger::new("probe", Wake::Webhook { hook: "probe".into() }, run("probe")))
    ///     .build()?;
    /// assert!(kernel.inventory().triggers.iter().all(|trigger| trigger.served));
    /// # Ok::<(), adk_kernel::KernelError>(())
    /// ```
    #[must_use]
    pub fn workflow(mut self, executor: Arc<dyn WorkflowExecutor>) -> Self {
        self.workflows.push(executor);
        self
    }

    /// Runs `tracker`, a site's KPI tracker, as the kernel's `kernel.kpi` process (spec 3.5
    /// §7.11; feature `charter`): its trigger ([`KpiTracker::trigger`](crate::charter::KpiTracker::trigger))
    /// on the six-field UTC cron `expr` for app `app_name`, and one
    /// [`KpiTrackerExecutor`](crate::charter::KpiTrackerExecutor) over every tracker registered,
    /// beside the other workflows. The tracker then shows in `ps`, keeps a cron watermark and
    /// waits out a freeze.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::InMemoryRunStore;
    /// use adk_kernel::Kernel;
    /// use adk_kernel::charter::{InMemoryCharterStore, InMemoryKpiStore, KpiTracker};
    ///
    /// let tracker = KpiTracker::new(uuid::Uuid::new_v4(), Arc::new(InMemoryCharterStore::new()), Arc::new(InMemoryKpiStore::new()));
    /// let kernel = Kernel::builder()
    ///     .run_store(Arc::new(InMemoryRunStore::new()))
    ///     .kpi_tracker(tracker, "bakery", "0 0 * * * *")
    ///     .build()?;
    /// let trigger = &kernel.inventory().triggers[0];
    /// assert_eq!((trigger.target.as_str(), trigger.served), ("kernel.kpi", true));
    /// # Ok::<(), adk_kernel::KernelError>(())
    /// ```
    #[cfg(feature = "charter")]
    #[must_use]
    pub fn kpi_tracker(
        mut self,
        tracker: crate::charter::KpiTracker,
        app_name: &str,
        expr: &str,
    ) -> Self {
        self.triggers.push(tracker.trigger(app_name, expr));
        self.kpi_trackers.push(tracker);
        self
    }

    /// Adds a wake source.
    #[must_use]
    pub fn wake_source(mut self, source: Arc<dyn WakeSource>) -> Self {
        self.wake_sources.push(source);
        self
    }

    /// Adds a standing trigger.
    #[must_use]
    pub fn trigger(mut self, trigger: Trigger) -> Self {
        self.triggers.push(trigger);
        self
    }

    /// Adds an event sink, such as an outbound `WebhookSink` (feature `webhooks`), that
    /// receives every later event through its own bounded queue (spec 3.2 §7.6).
    #[must_use]
    pub fn event_sink(mut self, sink: Arc<dyn EventSink>) -> Self {
        self.sinks.push(sink);
        self
    }

    /// Sets the source of goal progress and loop-guard verdicts for process views.
    #[must_use]
    pub fn progress_source(mut self, source: Arc<dyn ProgressSource>) -> Self {
        self.progress = Some(source);
        self
    }

    /// Sets the progress source of partition `partition` (spec 3.2 §7.8, §7.10): the
    /// kernel asks it, not the [`progress_source`](Self::progress_source), for the goal
    /// progress, loop-guard verdict and usage of that partition's processes — routed by the
    /// process's own partition — and hands it the process table and the ledger at start, as
    /// it does the main source. A partition without a source of its own falls back to the
    /// main source; its processes keep their partition.
    ///
    /// [`build`](Self::build) refuses a second source for the same partition, and
    /// [`Kernel::start`] warns about a partition the partition table does not hold.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::InMemoryRunStore;
    /// use adk_kernel::{Kernel, ProgressSource};
    ///
    /// struct Work;
    /// impl ProgressSource for Work {}
    ///
    /// let builder = || Kernel::builder().run_store(Arc::new(InMemoryRunStore::new()));
    /// assert!(builder().partition_progress_source("work", Arc::new(Work)).build().is_ok());
    /// let twice = builder()
    ///     .partition_progress_source("work", Arc::new(Work))
    ///     .partition_progress_source("work", Arc::new(Work))
    ///     .build();
    /// assert!(twice.is_err());
    /// ```
    #[must_use]
    pub fn partition_progress_source(
        mut self,
        partition: impl Into<PartitionId>,
        source: Arc<dyn ProgressSource>,
    ) -> Self {
        self.partition_progress.push((partition.into(), source));
        self
    }

    /// Adds a queue ingress the kernel runs while started, such as
    /// [`queue_wake_ingress`](crate::queue_wake_ingress).
    #[must_use]
    pub fn queue_ingress(mut self, ingress: QueueIngress) -> Self {
        self.queue_ingresses.push(ingress);
        self
    }

    /// Sets the agenda's store (spec 3.2 §7.5). Defaults to [`InMemoryAgendaStore`].
    #[must_use]
    pub fn agenda_store(mut self, store: Arc<dyn AgendaStore>) -> Self {
        self.agenda = Some(store);
        self
    }

    /// Binds `handle` to the built kernel's agenda, so a tool created before the kernel —
    /// the harness's `propose_followup` — reaches it (spec 3.2 §7.5, §10 HK1).
    #[must_use]
    pub fn agenda_handle(mut self, handle: AgendaHandle) -> Self {
        self.agenda_handles.push(handle);
        self
    }

    /// Hosts background sub-agents (`adk_core::subagent`): a parent agent's
    /// `start_subagent` runs another agent as a process of this kernel's `background`
    /// queue — or of the queue `config` names, when the kernel has it — with a budget slice
    /// carved from the parent's run, the parent's tools as its ceiling, and its status on
    /// the bus. Off by default, since a sub-agent works without a person watching it.
    ///
    /// Needs a [`session_service`](Self::session_service): a fork copies the parent's
    /// session, and a parent is told once by the notice its session holds.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use std::sync::Arc;
    /// use adk_core::{InMemoryRunStore, RunBudget};
    /// use adk_kernel::{Kernel, SubagentHandle};
    /// use adk_server::background::SubagentConfig;
    ///
    /// # fn example(runner: Arc<adk_runner::Runner>, sessions: Arc<dyn adk_session::SessionService>) -> adk_kernel::Result<()> {
    /// let handle = SubagentHandle::new(); // give the lead agent `SubagentTools::new(Arc::new(handle.clone()))`
    /// let kernel = Kernel::builder()
    ///     .run_store(Arc::new(InMemoryRunStore::new()))
    ///     .session_service(sessions)
    ///     .agent("lead", runner)
    ///     .subagents(SubagentConfig::default().with_default_budget(RunBudget::new().max_model_calls(20)))
    ///     .subagent_handle(handle)
    ///     .build()?;
    /// assert!(kernel.subagents().is_some());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn subagents(mut self, config: SubagentConfig) -> Self {
        self.subagents = Some(config);
        self
    }

    /// Binds `handle` to the built kernel's sub-agent host, so the sub-agent tools of an
    /// agent built before the kernel reach it.
    #[must_use]
    pub fn subagent_handle(mut self, handle: crate::subagents::SubagentHandle) -> Self {
        self.subagent_handles.push(handle);
        self
    }

    /// Sets where the agents a person adds are kept (spec 3.3 §5.7, §10 K7). Defaults to
    /// [`InMemoryAgentStore`](crate::stores::InMemoryAgentStore), which keeps nothing across
    /// a restart.
    #[must_use]
    pub fn agent_store(mut self, store: Arc<dyn crate::agents::AgentStore>) -> Self {
        self.agent_store = Some(store);
        self
    }

    /// Sets how the agents a person adds are built (spec 3.3 §5.7, §10 K7). Without one the
    /// kernel lists and removes agents but adds none.
    #[must_use]
    pub fn agent_factory(mut self, factory: Arc<dyn crate::agents::AgentFactory>) -> Self {
        self.agent_factory = Some(factory);
        self
    }

    /// Binds `handle` to the built kernel's agent table, so a tool created before the kernel
    /// — the harness's `propose_agent` — reaches it (spec 3.3 §10 K7), as
    /// [`agenda_handle`](Self::agenda_handle) does for `propose_followup`.
    #[must_use]
    pub fn agents_handle(mut self, handle: crate::agents::AgentsHandle) -> Self {
        self.agents_handles.push(handle);
        self
    }

    /// Sets where the daily review reads standing rules (spec 3.2 §9.1); `Harness::kernel`
    /// sets the harness's rule store.
    #[must_use]
    pub fn standing_rules(mut self, source: Arc<dyn crate::review::StandingRuleSource>) -> Self {
        self.rule_source = Some(source);
        self
    }

    /// Registers `consolidator` for `partition`: the kernel runs its consolidation tick
    /// there when [`ProactivityPolicy::consolidation`] is set (spec 3.2 §7.5, §10 HK2).
    #[must_use]
    pub fn consolidator(
        mut self,
        partition: impl Into<PartitionId>,
        consolidator: Arc<dyn Consolidator>,
    ) -> Self {
        self.consolidators.insert(partition.into(), consolidator);
        self
    }

    /// Supervises drivers (spec 3.2 §7.7): `Kernel::start` loads the mounted drivers and
    /// starts the eager ones, `Kernel::stop` stops them, and their state changes reach the
    /// kernel's bus and audit trail.
    #[cfg(feature = "drivers")]
    #[must_use]
    pub fn drivers(mut self, drivers: crate::drivers::DriverSupervisor) -> Self {
        self.drivers = Some(drivers);
        self
    }

    /// Registers `audience` for `partition` (spec 3.2 §7.10): the daily baseline pass puts
    /// the partition's observations to the person it names as
    /// [`AgendaOrigin::Observation`](crate::AgendaOrigin::Observation) questions, and a
    /// confirmation is remembered through it. Without one, observations stay at
    /// `/api/kernel/proc/observations` and nobody is asked.
    #[must_use]
    pub fn observation_audience(
        mut self,
        partition: impl Into<PartitionId>,
        audience: Arc<dyn ObservationAudience>,
    ) -> Self {
        self.audiences.insert(partition.into(), audience);
        self
    }

    /// Keeps the content-free activity ledger in `ledger` (spec 3.2 §7.10, feature `proc`):
    /// every event but `Health` writes its row, the [`ProgressSource`] gets the ledger at
    /// start so the hosted runtime writes its own activity, and rows are stamped on
    /// [`KernelConfig::clock`].
    #[cfg(feature = "proc")]
    #[must_use]
    pub fn ledger(mut self, ledger: Ledger) -> Self {
        self.ledger = Some(ledger);
        self
    }

    /// Runs the daily baseline pass under `policy` (spec 3.2 §7.10, feature
    /// `proc-baselines`). With a ledger and no policy, the pass runs under
    /// `BaselinePolicy::default()`; `BaselinePolicy::disabled()` turns it off.
    #[cfg(feature = "proc-baselines")]
    #[must_use]
    pub fn baseline_policy(mut self, policy: crate::proc::baselines::BaselinePolicy) -> Self {
        self.baselines = Some(policy);
        self
    }

    /// Words observations with `phraser`, a model used only after the deterministic
    /// detection (spec 3.2 §7.10, feature `proc-baselines`); without one the kernel's
    /// template words them.
    #[cfg(feature = "proc-baselines")]
    #[must_use]
    pub fn observation_phraser(
        mut self,
        phraser: Arc<dyn crate::proc::baselines::ObservationPhraser>,
    ) -> Self {
        self.phraser = Some(phraser);
        self
    }

    /// Sets the partition table (spec 3.2 §7.8). Defaults to one in memory. Give the kernel
    /// the [`Partitions`] its partition harnesses were built with, so their policies, the
    /// control plane and the daily review read one table.
    #[must_use]
    pub fn partitions(mut self, partitions: Partitions) -> Self {
        self.partitions = Some(partitions);
        self
    }

    /// Hosts `runner`, the harness of partition `partition`, as the target `target`, bound to
    /// the partition (spec 3.2 §7.8, K-I15): a process of another partition cannot run it,
    /// a spawn of it in the default partition runs in `partition`, and a run of it enqueued
    /// outside the kernel is listed in `partition`.
    #[must_use]
    pub fn partition_agent(
        mut self,
        partition: impl Into<PartitionId>,
        target: impl Into<String>,
        runner: Arc<Runner>,
    ) -> Self {
        let target = target.into();
        self.partition_targets.insert(target.clone(), partition.into());
        self.agents.insert(target, runner);
        self
    }

    /// Sets where the cron wakes of sleepers keep their cursors (spec 3.2 §7.4). Defaults to
    /// [`InMemoryCronWatermarkStore`], which keeps nothing across a restart.
    ///
    /// The kernel fires a sleeper's cron wake itself and keeps the expression's cursor here
    /// under `kernel:<expression>`. With a durable store shared by every replica, a restart
    /// or another replica fires each occurrence missed while no kernel ran once, as the
    /// sleepers' `missed` policies pick them, and never one that already fired.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::InMemoryRunStore;
    /// use adk_kernel::{InMemoryCronWatermarkStore, Kernel};
    ///
    /// let kernel = Kernel::builder()
    ///     .run_store(Arc::new(InMemoryRunStore::new()))
    ///     .watermark_store(Arc::new(InMemoryCronWatermarkStore::new()))
    ///     .build()
    ///     .unwrap();
    /// # let _ = kernel;
    /// ```
    #[must_use]
    pub fn watermark_store(mut self, store: Arc<dyn CronWatermarkStore>) -> Self {
        self.watermarks = Some(store);
        self
    }

    /// Takes every stateful store the builder has no other from `stores` (spec 3.2 §7.1): a
    /// store set on the builder, before or after, wins.
    ///
    /// | Builder store | From `stores` |
    /// |---|---|
    /// | [`run_store`](Self::run_store), [`process_store`](Self::process_store), [`schedule_store`](Self::schedule_store), [`spend_ledger`](Self::spend_ledger), [`agenda_store`](Self::agenda_store), [`watermark_store`](Self::watermark_store), [`agent_store`](Self::agent_store) | the store of the same name |
    /// | [`partitions`](Self::partitions) | a table over `partitions` |
    /// | the kill switch | [`KernelConfig::mirrored_governance`] over `governance`, unless [`governance`](Self::governance) is set, the configuration's is mirrored, or the bundle keeps `governance` in memory |
    /// | the control plane's settings store | `control`, unless the configuration names its own (`ControlPlaneConfig::with_control_store`) |
    ///
    /// The approval service, the drivers' supervisor and the activity ledger are built by the
    /// host over `approvals`, `drivers` and `ledger`, with its own routing, home and key.
    /// A runner built before the kernel shares the kernel's kill switch through
    /// `kernel.config().governance`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_kernel::Kernel;
    /// use adk_kernel::stores::{KernelStores, StoreOrigin};
    ///
    /// let kernel = Kernel::builder().stores(&KernelStores::in_memory()).build()?;
    /// assert!(kernel.store_uses().iter().all(|used| used.origin == StoreOrigin::Bundle));
    /// # Ok::<(), adk_kernel::KernelError>(())
    /// ```
    #[must_use]
    pub fn stores(mut self, stores: &KernelStores) -> Self {
        self.bundle = Some(stores.clone());
        self
    }

    /// Refuses to build a kernel that would keep a stateful store in memory (spec 3.2
    /// §7.1): one the builder defaulted, one its [`KernelStores`] keeps in memory, or a kill
    /// switch that is not mirrored. Without it, the kernel's [`inventory`](Kernel::inventory)
    /// warns about each such store when the kernel starts. [`Kernel::store_uses`] reports each store either way.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::InMemoryRunStore;
    /// use adk_kernel::Kernel;
    ///
    /// let refused = Kernel::builder()
    ///     .run_store(Arc::new(InMemoryRunStore::new()))
    ///     .require_durable()
    ///     .build()
    ///     .unwrap_err();
    /// assert!(refused.to_string().contains("`process_store`"));
    /// ```
    #[must_use]
    pub fn require_durable(mut self) -> Self {
        self.require_durable = true;
        self
    }

    /// Files signals in `partition` through `store` (spec 3.5 §7.10; feature `charter`):
    /// [`Kernel::signal_sink`] returns the partition's sink, and the kernel's
    /// [`inventory`](Kernel::inventory) knows the partition's signal triggers can fire.
    /// Registering a partition again replaces its store.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::InMemoryRunStore;
    /// use adk_kernel::Kernel;
    /// use adk_kernel::charter::InMemorySignalStore;
    ///
    /// let kernel = Kernel::builder()
    ///     .run_store(Arc::new(InMemoryRunStore::new()))
    ///     .signals(Arc::new(InMemorySignalStore::new()), "back-office")
    ///     .build()?;
    /// assert_eq!(kernel.signal_sink("back-office")?.partition().as_str(), "back-office");
    /// assert!(kernel.signal_sink("public").is_err());
    /// # Ok::<(), adk_kernel::KernelError>(())
    /// ```
    #[cfg(feature = "charter")]
    #[must_use]
    pub fn signals(
        mut self,
        store: Arc<dyn crate::charter::SignalStore>,
        partition: impl Into<PartitionId>,
    ) -> Self {
        self.signal_stores.insert(partition.into(), store);
        self
    }

    /// Adds `warning` to the kernel's [`inventory`](Kernel::inventory), logged when the kernel
    /// starts: something the host or a kit would otherwise leave silent, such as a job it does
    /// not schedule and why.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::InMemoryRunStore;
    /// use adk_kernel::Kernel;
    /// use adk_kernel::inventory::InventoryWarning;
    ///
    /// let kernel = Kernel::builder()
    ///     .run_store(Arc::new(InMemoryRunStore::new()))
    ///     .inventory_warning(InventoryWarning::new("site.job_unscheduled", "no channel for the digest"))
    ///     .build()?;
    /// assert!(kernel.inventory().warnings.iter().any(|warning| warning.code == "site.job_unscheduled"));
    /// # Ok::<(), adk_kernel::KernelError>(())
    /// ```
    #[must_use]
    pub fn inventory_warning(mut self, warning: InventoryWarning) -> Self {
        self.inventory_warnings.push(warning);
        self
    }

    /// Builds the kernel. Nothing runs until [`Kernel::start`].
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Config`] when no run store is set, the control plane
    /// configuration is refused (K-I18), a partition has two progress sources, or
    /// [`require_durable`](Self::require_durable) is set and a stateful store would be kept
    /// in memory, naming each.
    pub fn build(self) -> Result<Kernel> {
        let mut slots = Slots { uses: Vec::new(), bundle: self.bundle.as_ref() };
        let runs = slots.take("run_store", self.runs, "runs", |b| Arc::clone(&b.runs)).ok_or_else(
            || KernelError::Config {
                reason: "a kernel needs a durable run store; call KernelBuilder::run_store or \
                         KernelBuilder::stores"
                    .into(),
            },
        )?;
        let processes: Arc<dyn ProcessStore> = slots
            .take("process_store", self.processes, "processes", |b| Arc::clone(&b.processes))
            .unwrap_or_else(|| {
                slots.defaulted("process_store", Arc::new(InMemoryProcessStore::new()))
            });
        let schedules =
            slots.take("schedule_store", self.schedules, "schedules", |b| Arc::clone(&b.schedules));
        let spend = slots.take("spend_ledger", self.spend, "spend", |b| Arc::clone(&b.spend));
        let agenda_store: Arc<dyn AgendaStore> = slots
            .take("agenda_store", self.agenda, "agenda", |b| Arc::clone(&b.agenda))
            .unwrap_or_else(|| {
                slots.defaulted("agenda_store", Arc::new(InMemoryAgendaStore::new()))
            });
        let partitions = slots
            .take("partitions", self.partitions, "partitions", |b| {
                Partitions::new(Arc::clone(&b.partitions))
            })
            .unwrap_or_else(|| slots.defaulted("partitions", Partitions::in_memory()));
        let watermarks: Arc<dyn CronWatermarkStore> = slots
            .take("watermark_store", self.watermarks, "watermarks", |b| Arc::clone(&b.watermarks))
            .unwrap_or_else(|| {
                slots.defaulted("watermark_store", Arc::new(InMemoryCronWatermarkStore::new()))
            });
        let agent_store: Arc<dyn crate::agents::AgentStore> = slots
            .take("agent_store", self.agent_store, "agents", |b| Arc::clone(&b.agents))
            .unwrap_or_else(|| {
                slots.defaulted("agent_store", Arc::new(crate::stores::InMemoryAgentStore::new()))
            });
        let mut config = self.config;
        slots.governance(&mut config, self.governance);
        slots.control_store(&mut config);
        let store_uses = slots.finish(self.require_durable)?;
        let mut partition_progress = BTreeMap::new();
        for (partition, source) in self.partition_progress {
            if partition_progress.contains_key(&partition) {
                return Err(KernelError::Config {
                    reason: format!(
                        "partition `{partition}` has two progress sources; register one per \
                         partition with KernelBuilder::partition_progress_source"
                    ),
                });
            }
            partition_progress.insert(partition, source);
        }
        config.control.validate()?;
        let mut names = std::collections::BTreeSet::new();
        if config.queues.is_empty()
            || !config.queues.iter().all(|queue| names.insert(queue.as_str().to_string()))
        {
            return Err(KernelError::Config {
                reason: format!(
                    "the kernel needs at least one queue class and each once; got {:?}",
                    config.queues
                ),
            });
        }
        if let Some(trail) = &self.audit {
            partitions.attach_audit(trail.clone());
        }
        let bus = EventBus::default();
        for sink in self.sinks {
            bus.add_sink(sink);
        }
        let mut inventory_warnings = self.inventory_warnings;
        if let Some(approvals) = &self.approvals {
            // Every held call reaches the inbox and the bus, however the host built the
            // service: a call no one can see is a process no one can resume.
            let operator =
                ApprovalPolicy::new([ApproverSelector::group(crate::agenda::OPERATOR_GROUP)])
                    .allow_self_approval();
            if !approvals.route_unrouted(Arc::new(operator)) {
                inventory_warnings.push(InventoryWarning::new(
                    InventoryWarning::APPROVALS_UNROUTED,
                    "the approval service takes no router from the kernel: a call it holds \
                     with no route of its own reaches no inbox. Build it with `with_router`",
                ));
            }
            if !approvals.add_notifier(Arc::new(crate::bus::ApprovalEvents::new(bus.clone()))) {
                inventory_warnings.push(InventoryWarning::new(
                    InventoryWarning::APPROVALS_UNHEARD,
                    "the approval service takes no notifier from the kernel: no `held` or \
                     `decided` event is published",
                ));
            }
        }
        let trigger_names = self.triggers.iter().map(|trigger| trigger.name.clone()).collect();
        let trigger_crons = trigger_cron_sources(
            &self.triggers,
            &self.wake_sources,
            &watermarks,
            config.salted_cron_jitter(),
        )?;
        #[cfg(feature = "proc")]
        let ledger = self.ledger.map(|ledger| ledger.with_clock(Arc::clone(&config.clock)));
        #[cfg(feature = "proc")]
        if let Some(ledger) = &ledger {
            bus.add_sink(Arc::new(LedgerEventSink::new(
                ledger.clone(),
                runs.clone(),
                processes.clone(),
            )));
        }
        let kernel_id = format!("kernel-{}", uuid::Uuid::new_v4());
        // The kernel's own proposers reach the agenda through this handle, bound below.
        let kernel_agenda = AgendaHandle::new();
        #[cfg(feature = "proc-baselines")]
        let proc = ledger.as_ref().map(|ledger| {
            let mut pass = crate::proc::baselines::BaselinePass::new(
                ledger.clone(),
                self.baselines.clone().unwrap_or_default(),
            );
            if let Some(phraser) = self.phraser.clone() {
                pass = pass.with_phraser(phraser);
            }
            Arc::new(crate::proc::baselines::ProcRuntime::new(
                pass,
                bus.clone(),
                self.audit.clone(),
                kernel_id.clone(),
                config.app_name.clone(),
                kernel_agenda.clone(),
            ))
        });
        let router = self
            .triggers
            .into_iter()
            .fold(WakeRouter::new(runs.clone(), processes.clone()), WakeRouter::with_trigger)
            .with_bus(bus.clone())
            .with_clock(Arc::clone(&config.clock));
        // The agents a person adds share one live target table with every worker (spec 3.3
        // §10 S4).
        let targets = Arc::new(crate::agents::Targets::new(
            self.partition_targets,
            Some(Arc::clone(&agent_store)),
        ));
        let sup = Arc::new(Supervision {
            app_name: config.app_name.clone(),
            kernel_id,
            queues: config.queues.clone(),
            runs: runs.clone(),
            processes,
            bus,
            governance: config.governance.clone(),
            audit: self.audit.clone(),
            sessions: self.sessions.clone(),
            progress: self.progress,
            partition_progress,
            workers: std::sync::OnceLock::new(),
            handles: std::sync::Mutex::new(Vec::new()),
            draining: std::sync::atomic::AtomicBool::new(false),
            local: std::sync::Mutex::new(HashMap::new()),
            roots_changed: tokio::sync::Notify::new(),
            watched: std::sync::Mutex::new(BTreeMap::new()),
            clock: Arc::clone(&config.clock),
            proactivity: config.proactivity.clone(),
            quiet_hours: config.quiet_hours,
            quotas: config.quotas.clone(),
            agenda: agenda_store,
            admission: tokio::sync::Mutex::new(()),
            rule_source: self.rule_source,
            reviewed: std::sync::Mutex::new(None),
            crons: std::sync::Mutex::new(BTreeMap::new()),
            watermarks,
            cron_started: std::sync::Mutex::new(None),
            cron_jitter: config.salted_cron_jitter(),
            triggers: trigger_names,
            #[cfg(feature = "proc-baselines")]
            proc: proc.clone(),
            targets: Arc::clone(&targets),
            partitions: partitions.clone(),
            control: Arc::new(crate::control::LastRead::new(config.control.control_store.clone())),
        });
        let run_finished = Arc::new(RunFinishedWakeSource::new());
        let subagent_backend = self.subagents.is_some().then(|| {
            Arc::new(crate::subagents::KernelSubagentBackend {
                processes: ProcessTable::supervised(Arc::clone(&sup), spend.clone()),
                sup: Arc::clone(&sup),
                kernel: std::sync::OnceLock::new(),
            })
        });
        let subagents = match (self.subagents, &subagent_backend) {
            (Some(mut sub_config), Some(backend)) => {
                let Some(sessions) = self.sessions.clone() else {
                    return Err(KernelError::Config {
                        reason: "background sub-agents need a session service; call \
                                 KernelBuilder::session_service"
                            .into(),
                    });
                };
                // A sub-agent runs on one of this kernel's queues.
                if !config.queues.iter().any(|queue| queue.as_str() == sub_config.queue) {
                    sub_config.queue = config
                        .queues
                        .iter()
                        .find(|queue| queue.as_str() == QueueClass::BACKGROUND)
                        .unwrap_or(&config.queues[0])
                        .as_str()
                        .to_string();
                }
                let backend: Arc<dyn SubagentBackend> = backend.clone();
                Some(DurableSubagents::new(runs.clone(), sessions, backend, sub_config))
            }
            _ => None,
        };
        for handle in &self.subagent_handles {
            if let Some(subagents) = &subagents {
                handle.bind(subagents);
            }
        }
        let hooks = Arc::new(KernelHooks {
            sup: Arc::clone(&sup),
            run_finished: run_finished.clone(),
            subagents: subagents.clone(),
        });
        let mut chain = self.workflows;
        #[cfg(feature = "charter")]
        if !self.kpi_trackers.is_empty() {
            chain.push(Arc::new(crate::charter::KpiTrackerExecutor::new(self.kpi_trackers)));
        }
        let caller_workflows: Option<Arc<dyn WorkflowExecutor>> = match chain.len() {
            0 | 1 => chain.pop(),
            _ => Some(Arc::new(WorkflowChain(chain))),
        };
        // The consolidation tick's workflow sits before the caller's (spec 3.2 §7.5).
        let consolidators = Arc::new(self.consolidators);
        let user_workflows = if consolidators.is_empty() {
            caller_workflows.clone()
        } else {
            Some(Arc::new(ConsolidationExecutor::new(
                Arc::clone(&sup),
                Arc::clone(&consolidators),
                kernel_agenda.clone(),
                caller_workflows.clone(),
            )) as Arc<dyn WorkflowExecutor>)
        };
        let workflows = Arc::new(KernelWorkflows {
            user: user_workflows,
            wake: KernelWakeExecutor::new(router.clone()),
            #[cfg(feature = "proc-baselines")]
            proc,
        });
        let workers = config
            .queues
            .iter()
            .map(|queue| {
                let mut worker = DurableWorker::new(runs.clone())
                    .with_config(config.worker_config(queue))
                    .with_clock(Arc::clone(&config.clock))
                    .with_governance(config.governance.clone())
                    .with_workflows(workflows.clone())
                    .with_hooks(hooks.clone());
                if let Some(trail) = &self.audit {
                    worker = worker.with_audit(trail.clone());
                }
                for (target, runner) in &self.agents {
                    worker = worker.with_agent(target.clone(), runner.clone());
                }
                // The agents a person adds, hosted while the kernel runs (spec 3.3 §10 S4).
                worker = worker.with_agent_table(targets.table.clone());
                (queue.clone(), worker)
            })
            .collect();
        let _ = sup.workers.set(workers);
        let mut wake_sources = self.wake_sources;
        wake_sources.extend(trigger_crons);
        wake_sources.push(run_finished);
        let processes = ProcessTable::supervised(Arc::clone(&sup), spend);
        let agenda = Agenda::new(
            Arc::clone(&sup),
            processes.clone(),
            self.approvals.clone(),
            self.audiences,
        );
        for handle in self.agenda_handles.iter().chain([&kernel_agenda]) {
            handle.bind(&agenda);
        }
        let consolidation = (!consolidators.is_empty())
            .then(|| ConsolidationTicker::new(Arc::clone(&sup), processes.clone(), consolidators));
        let adds_agents = self.agent_factory.is_some();
        let agent_table = crate::agents::Agents::new(crate::agents::AgentsParts {
            sup: Arc::clone(&sup),
            processes: processes.clone(),
            agenda: agenda.clone(),
            targets,
            store: agent_store,
            factory: self.agent_factory,
            approvals: self.approvals.clone(),
            statics: self.agents.keys().cloned().collect(),
            start_modes: config.control.start_modes.clone(),
            workflows: caller_workflows.clone(),
            #[cfg(feature = "drivers")]
            drivers: self.drivers.clone(),
            #[cfg(feature = "proc")]
            ledger: ledger.clone(),
        });
        for handle in &self.agents_handles {
            handle.bind(&agent_table);
        }
        let kernel = Kernel {
            inner: Arc::new(KernelInner {
                config,
                sup,
                processes,
                agenda,
                partitions,
                router,
                schedules,
                store_uses,
                approvals: self.approvals,
                sessions: self.sessions,
                agents: self.agents,
                agent_table,
                workflows: caller_workflows,
                wake_sources,
                queue_ingresses: self.queue_ingresses,
                adds_agents,
                #[cfg(feature = "charter")]
                signal_stores: self.signal_stores,
                inventory_warnings,
                consolidation,
                #[cfg(feature = "drivers")]
                drivers: self.drivers,
                runtime: tokio::sync::Mutex::new(Runtime::default()),
                status: Arc::new(RwLock::new(Status::default())),
                #[cfg(feature = "proc")]
                ledger,
                subagents,
                serves_routes: std::sync::atomic::AtomicBool::new(false),
            }),
        };
        if let Some(backend) = subagent_backend {
            let _ = backend.kernel.set(Arc::downgrade(&kernel.inner));
        }
        Ok(kernel)
    }
}

/// The stateful stores a [`KernelBuilder`] resolves: each set one, else its bundle's, else
/// one in memory, with where each came from.
struct Slots<'a> {
    uses: Vec<StoreUse>,
    bundle: Option<&'a KernelStores>,
}

impl Slots<'_> {
    /// `set`, else the bundle's store `field` picks, recording which; `None` with neither.
    fn take<T>(
        &mut self,
        store: &str,
        set: Option<T>,
        field: &str,
        pick: impl FnOnce(&KernelStores) -> T,
    ) -> Option<T> {
        if set.is_some() {
            self.uses.push(StoreUse::new(store, StoreOrigin::Set, false));
            return set;
        }
        let bundle = self.bundle?;
        self.uses.push(self.bundled(store, field));
        Some(pick(bundle))
    }

    /// `memory`, recorded as the store the builder defaulted.
    fn defaulted<T>(&mut self, store: &str, memory: T) -> T {
        self.uses.push(StoreUse::new(store, StoreOrigin::Defaulted, true));
        memory
    }

    fn bundled(&self, store: &str, field: &str) -> StoreUse {
        let bundle = self.bundle.expect("only called with a bundle");
        let mut used = StoreUse::new(store, StoreOrigin::Bundle, bundle.is_in_memory(field));
        used.bundle = Some(bundle.label().to_string());
        used
    }

    /// The kill switch: the one set, a mirrored configuration's, else mirrored over the
    /// bundle's governance store when it is durable; one held in this process otherwise.
    fn governance(&mut self, config: &mut KernelConfig, set: Option<GovernanceControl>) {
        let used = match (set, self.bundle) {
            (Some(control), _) => {
                config.governance = control;
                StoreUse::new("governance", StoreOrigin::Set, !config.governance.is_mirrored())
            }
            (None, _) if config.governance.is_mirrored() => {
                StoreUse::new("governance", StoreOrigin::Set, false)
            }
            (None, Some(bundle)) => {
                if !bundle.is_in_memory("governance") {
                    config.governance =
                        KernelConfig::mirrored_governance(Arc::clone(&bundle.governance));
                }
                self.bundled("governance", "governance")
            }
            (None, None) => StoreUse::new("governance", StoreOrigin::Defaulted, true),
        };
        self.uses.push(used);
    }

    /// The control plane's settings store: the configuration's own, else the bundle's.
    fn control_store(&mut self, config: &mut KernelConfig) {
        let used = if !config.control.has_default_control_store() {
            StoreUse::new("control_store", StoreOrigin::Set, false)
        } else if let Some(bundle) = self.bundle {
            config.control.control_store = Arc::clone(&bundle.control);
            self.bundled("control_store", "control")
        } else {
            StoreUse::new("control_store", StoreOrigin::Defaulted, true)
        };
        self.uses.push(used);
    }

    /// The record of every store, refused when `require_durable` and one is held in memory;
    /// the inventory warns about each when the kernel starts.
    fn finish(self, require_durable: bool) -> Result<Vec<StoreUse>> {
        if require_durable {
            let held: Vec<String> = self
                .uses
                .iter()
                .filter(|used| used.in_memory)
                .map(|used| {
                    let why = match (used.origin, &used.bundle) {
                        (StoreOrigin::Bundle, Some(label)) => {
                            format!("the stores `{label}` keep it in memory")
                        }
                        (StoreOrigin::Set, _) => "the kill switch is not mirrored".to_string(),
                        _ => format!("defaulted; set it with {}", store_remedy(&used.store)),
                    };
                    format!("`{}` ({why})", used.store)
                })
                .collect();
            if !held.is_empty() {
                return Err(KernelError::Config {
                    reason: format!(
                        "the kernel requires durable stores, and these would lose their state \
                         on a restart: {}; give the builder durable stores with \
                         KernelBuilder::stores(&KernelStores::open(url)), or set each",
                        held.join(", ")
                    ),
                });
            }
        }
        Ok(self.uses)
    }
}

/// The builder setter that gives a kernel its `store` durably.
fn store_remedy(store: &str) -> &'static str {
    match store {
        "governance" => "KernelBuilder::governance with KernelConfig::mirrored_governance",
        "control_store" => "ControlPlaneConfig::with_control_store",
        "partitions" => "KernelBuilder::partitions",
        "process_store" => "KernelBuilder::process_store",
        "agenda_store" => "KernelBuilder::agenda_store",
        "watermark_store" => "KernelBuilder::watermark_store",
        "agent_store" => "KernelBuilder::agent_store",
        "schedule_store" => "KernelBuilder::schedule_store",
        "spend_ledger" => "KernelBuilder::spend_ledger",
        _ => "KernelBuilder::run_store",
    }
}

/// The kernel's own source for each cron expression of `triggers` no source in `sources`
/// ticks on (spec 3.2 §7.4, spec 3.5 §7.11): one per expression, so every trigger on it
/// matches each tick once, planned with the widest missed-tick policy of its triggers, its
/// cursor kept in `watermarks` across restarts, each tick delayed by `jitter`.
fn trigger_cron_sources(
    triggers: &[Trigger],
    sources: &[Arc<dyn WakeSource>],
    watermarks: &Arc<dyn CronWatermarkStore>,
    jitter: Option<Jitter>,
) -> Result<Vec<Arc<dyn WakeSource>>> {
    let covered: std::collections::BTreeSet<&str> =
        sources.iter().filter_map(|source| source.cron_expression()).collect();
    let mut crons: BTreeMap<&str, adk_core::schedule::MissedFirePolicy> = BTreeMap::new();
    for trigger in triggers {
        if let Wake::Cron { expr, missed } = &trigger.wake
            && !covered.contains(expr.as_str())
        {
            let widest = crons
                .get(expr.as_str())
                .map_or(*missed, |held| crate::wake::widest_policy(*held, *missed));
            crons.insert(expr, widest);
        }
    }
    crons
        .into_iter()
        .map(|(expr, missed)| {
            let name =
                format!("trigger-cron:{}", expr.split_whitespace().collect::<Vec<_>>().join("_"));
            let watermark = SourceWatermark::new(Arc::clone(watermarks), name.clone());
            let mut source = CronWakeSource::watermarked(name, expr, missed, Arc::new(watermark))?;
            if let Some(jitter) = jitter {
                source = source.with_jitter(jitter);
            }
            Ok(Arc::new(source) as Arc<dyn WakeSource>)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use adk_core::{InMemoryRunStore, NewRun};
    use serde_json::json;

    use super::*;
    use crate::process::{ProcessKind, ProcessSpec};
    use crate::wake::WakeSet;

    async fn eventually(what: &str, mut probe: impl FnMut() -> bool) {
        let started = tokio::time::Instant::now();
        while started.elapsed() < Duration::from_secs(3) {
            if probe() {
                return;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        panic!("timed out waiting for {what}");
    }

    /// Two kernels built from the defaults in one process and one home both start: the
    /// defaults serve no control plane, so neither takes the other's socket or pipe.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn kernels_built_from_the_defaults_share_a_home() {
        let home = tempfile::tempdir().unwrap();
        let config = KernelConfig::default().with_home(home.path());
        assert_eq!((config.control.socket.as_deref(), config.control.http), (None, None));
        let build = || {
            Kernel::builder()
                .config(config.clone())
                .run_store(Arc::new(InMemoryRunStore::new()))
                .build()
                .unwrap()
        };
        let (first, second) = (build(), build());
        first.start().await.unwrap();
        second.start().await.unwrap();
        assert!(!home.path().join(ControlPlaneConfig::DEFAULT_SOCKET).exists());
        second.stop().await.unwrap();
        first.stop().await.unwrap();

        // Asked for, the socket at the home is still one kernel's.
        #[cfg(unix)]
        {
            let served = config.with_control(ControlPlaneConfig::default());
            let build = || {
                Kernel::builder()
                    .config(served.clone())
                    .run_store(Arc::new(InMemoryRunStore::new()))
                    .build()
                    .unwrap()
            };
            let (first, second) = (build(), build());
            first.start().await.unwrap();
            let error = second.start().await.unwrap_err();
            assert!(error.to_string().contains("already listens"), "{error}");
            first.stop().await.unwrap();
        }
    }

    /// A shared governance store whose reads answer after `delay`, and fail while unreachable.
    struct SlowGovernanceStore {
        inner: Arc<adk_core::InMemoryGovernanceStateStore>,
        delay: Duration,
        reachable: Arc<std::sync::atomic::AtomicBool>,
    }

    impl SlowGovernanceStore {
        fn over(inner: &Arc<adk_core::InMemoryGovernanceStateStore>, delay: Duration) -> Self {
            Self {
                inner: Arc::clone(inner),
                delay,
                reachable: Arc::new(std::sync::atomic::AtomicBool::new(true)),
            }
        }
    }

    #[async_trait]
    impl GovernanceStateStore for SlowGovernanceStore {
        async fn get(
            &self,
            scope: &adk_core::GovernanceScope,
        ) -> adk_core::Result<Option<adk_core::GovernanceState>> {
            tokio::time::sleep(self.delay).await;
            if !self.reachable.load(Ordering::SeqCst) {
                return Err(adk_core::AdkError::session("the governance store is unreachable"));
            }
            self.inner.get(scope).await
        }

        async fn set(
            &self,
            scope: adk_core::GovernanceScope,
            expected_epoch: u64,
            frozen: bool,
            reason: Option<String>,
            issued_by: Option<adk_core::SubjectRef>,
        ) -> adk_core::Result<adk_core::GovernanceState> {
            self.inner.set(scope, expected_epoch, frozen, reason, issued_by).await
        }

        async fn list(&self) -> adk_core::Result<Vec<adk_core::GovernanceState>> {
            self.inner.list().await
        }
    }

    /// A run no worker claims for an hour, so its process stays a queued sleeper.
    fn sleeper() -> NewRun {
        NewRun::new("background", "adk-rust", "alice", "adk-rust", json!({ "text": "x" }))
            .with_not_before(chrono::Utc::now() + chrono::Duration::hours(1))
    }

    fn operator() -> AuditActor {
        AuditActor::subject(adk_core::SubjectRef::human("operator"))
    }

    /// K9's race: work spawned as soon as `start` returns is decided by the mirrored store,
    /// even when the store answers slower than the rest of the start-up, rather than refused
    /// as never read.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn work_spawned_once_start_returns_is_not_refused_as_never_read() {
        let store = Arc::new(adk_core::InMemoryGovernanceStateStore::new());
        let slow = SlowGovernanceStore::over(&store, Duration::from_millis(500));
        let kernel = Kernel::builder()
            .config(
                KernelConfig::default()
                    .with_governance(KernelConfig::mirrored_governance(Arc::new(slow))),
            )
            .run_store(Arc::new(InMemoryRunStore::new()))
            .build()
            .unwrap();
        kernel.start().await.unwrap();
        let spawned =
            kernel.processes().spawn(sleeper(), ProcessSpec::new(ProcessKind::Interactive)).await;
        assert!(spawned.is_ok(), "{:?}", spawned.err());
        kernel.stop().await.unwrap();
    }

    /// The kill switch stays fail-closed: a kernel whose store cannot be read starts and
    /// refuses work until its mirror reads the store.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_kernel_whose_governance_store_is_unreachable_refuses_work_until_it_is_read() {
        let store = Arc::new(adk_core::InMemoryGovernanceStateStore::new());
        let slow = SlowGovernanceStore::over(&store, Duration::ZERO);
        let reachable = Arc::clone(&slow.reachable);
        reachable.store(false, Ordering::SeqCst);
        let kernel = Kernel::builder()
            .config(
                KernelConfig::default()
                    .with_governance(KernelConfig::mirrored_governance(Arc::new(slow))),
            )
            .run_store(Arc::new(InMemoryRunStore::new()))
            .build()
            .unwrap();
        kernel.start().await.unwrap();
        let refused = kernel
            .processes()
            .spawn(sleeper(), ProcessSpec::new(ProcessKind::Interactive))
            .await
            .unwrap_err();
        assert!(
            matches!(&refused, KernelError::Frozen { reason } if reason.contains("last read never")),
            "{refused:?}"
        );

        reachable.store(true, Ordering::SeqCst);
        let started = tokio::time::Instant::now();
        while kernel.config().governance.check().is_err() {
            assert!(started.elapsed() < Duration::from_secs(3), "the mirror never read the store");
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        kernel
            .processes()
            .spawn(sleeper(), ProcessSpec::new(ProcessKind::Interactive))
            .await
            .unwrap();
        kernel.stop().await.unwrap();
    }

    /// A replica that starts while the replicated freeze is in force reads it before it wakes
    /// anything: the processes the freeze parked stay parked until the unfreeze.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_replica_started_during_a_freeze_keeps_the_frozen_processes_parked() {
        let store = Arc::new(adk_core::InMemoryGovernanceStateStore::new());
        let runs: Arc<dyn DurableRunStore> = Arc::new(InMemoryRunStore::new());
        let processes: Arc<dyn ProcessStore> = Arc::new(InMemoryProcessStore::new());
        let replica = |delay: Duration| {
            let control = KernelConfig::mirrored_governance(Arc::new(SlowGovernanceStore::over(
                &store, delay,
            )));
            Kernel::builder()
                .config(KernelConfig::default().with_governance(control))
                .run_store(Arc::clone(&runs))
                .process_store(Arc::clone(&processes))
                .build()
                .unwrap()
        };
        let first = replica(Duration::ZERO);
        first.start().await.unwrap();
        let process = first
            .processes()
            .spawn(sleeper(), ProcessSpec::new(ProcessKind::Interactive))
            .await
            .unwrap();
        let pid = process.meta.pid.clone();
        processes.put(process.meta.with_suspension(Suspension::Freeze)).await.unwrap();
        first.freeze("incident 9", operator()).await.unwrap();
        first.stop().await.unwrap();

        // The new replica's store answers slower than the rest of its start-up.
        let second = replica(Duration::from_millis(300));
        second.start().await.unwrap();
        let parked = processes.get(&pid).await.unwrap().unwrap();
        assert_eq!(parked.suspended_by, Some(Suspension::Freeze));
        let refused = second
            .processes()
            .spawn(sleeper(), ProcessSpec::new(ProcessKind::Interactive))
            .await
            .unwrap_err();
        assert!(
            matches!(&refused, KernelError::Frozen { reason } if reason == "incident 9"),
            "{refused:?}"
        );

        second.unfreeze(operator()).await.unwrap();
        assert_eq!(processes.get(&pid).await.unwrap().unwrap().suspended_by, None);
        second.stop().await.unwrap();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_file_wake_spawned_after_start_is_watched_until_no_sleeper_needs_it() {
        let dir = tempfile::tempdir().unwrap();
        let kernel = Kernel::builder()
            .config(
                KernelConfig::default()
                    // Long enough that only the spawn's signal can explain a prompt watch.
                    .with_scheduler_tick(Duration::from_secs(60))
                    .with_control(ControlPlaneConfig::default().without_socket()),
            )
            .run_store(Arc::new(InMemoryRunStore::new()))
            .build()
            .unwrap();
        kernel.start().await.unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        assert!(kernel.inner.sup.watched_roots().is_empty());

        let wake = WakeSet::any_of([Wake::FileChange {
            root: dir.path().to_path_buf(),
            glob: "notes.md".into(),
            debounce: Duration::from_millis(100),
        }]);
        // Not claimable for an hour: it stays a queued sleeper the whole test.
        let run =
            NewRun::new("background", "adk-rust", "alice", "adk-rust", json!({ "text": "x" }))
                .with_not_before(chrono::Utc::now() + chrono::Duration::hours(1));
        let process = kernel
            .processes()
            .spawn(run, ProcessSpec::new(ProcessKind::Interactive).with_wake(wake))
            .await
            .unwrap();
        eventually("the root to be watched", || kernel.inner.sup.watched_roots() == [root.clone()])
            .await;

        kernel.processes().kill(&process.meta.pid, "not needed").await.unwrap();
        eventually("the root to be dropped", || kernel.inner.sup.watched_roots().is_empty()).await;
        kernel.stop().await.unwrap();
    }

    /// A standing cron trigger fires with no source registered for it: the kernel adds one
    /// watermarked source per expression, so two triggers on one expression each fire once
    /// per tick, and a registered source on the expression takes its place (spec 3.5 §7.11).
    /// The control plane's address is readable once it listens.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_standing_cron_trigger_fires_through_the_kernels_own_source() {
        let every_second = "* * * * * *";
        let wake =
            || Wake::Cron { expr: every_second.into(), missed: adk_core::MissedFirePolicy::Skip };
        let template = |target: &str| {
            NewRun::new("background", "adk-rust", "alice", target, json!({ "text": "tick" }))
        };
        let runs: Arc<dyn DurableRunStore> = Arc::new(InMemoryRunStore::new());
        let loopback: std::net::SocketAddr = "127.0.0.1:0".parse().unwrap();
        let kernel =
            Kernel::builder()
                .config(KernelConfig::default().with_control(
                    ControlPlaneConfig::default().without_socket().with_http(loopback),
                ))
                .run_store(Arc::clone(&runs))
                .trigger(Trigger::new("digest-a", wake(), template("digest-a")))
                .trigger(Trigger::new("digest-b", wake(), template("digest-b")))
                .build()
                .unwrap();
        let crons: Vec<&str> =
            kernel.inner.wake_sources.iter().filter_map(|s| s.cron_expression()).collect();
        assert_eq!(crons, [every_second], "one source for the expression");
        assert_eq!(kernel.control_addr().await, None, "nothing listens before the start");
        kernel.start().await.unwrap();
        let addr = kernel.control_addr().await.expect("the control plane listens");
        assert_ne!(addr.port(), 0, "the bound port, not the configured 0");

        let started = tokio::time::Instant::now();
        let fired = loop {
            let targets: Vec<String> = runs
                .list(adk_core::RunFilter::default())
                .await
                .unwrap()
                .into_iter()
                .map(|run| run.target)
                .collect();
            if ["digest-a", "digest-b"].iter().all(|t| targets.iter().any(|run| run == t)) {
                break targets;
            }
            assert!(started.elapsed() < Duration::from_secs(5), "no trigger fired: {targets:?}");
            tokio::time::sleep(Duration::from_millis(50)).await;
        };
        kernel.stop().await.unwrap();
        let count = |t: &str| fired.iter().filter(|run| *run == t).count();
        assert!(count("digest-a").abs_diff(count("digest-b")) <= 1, "{fired:?}");

        // A registered source on the expression takes the kernel's place.
        let watermarks: Arc<dyn CronWatermarkStore> = Arc::new(InMemoryCronWatermarkStore::new());
        let own = CronWakeSource::watermarked(
            "mine",
            every_second,
            adk_core::MissedFirePolicy::Skip,
            Arc::new(SourceWatermark::new(watermarks, "mine")),
        )
        .unwrap();
        let kernel = Kernel::builder()
            .run_store(Arc::new(InMemoryRunStore::new()))
            .wake_source(Arc::new(own))
            .trigger(Trigger::new("digest-a", wake(), template("digest-a")))
            .build()
            .unwrap();
        let names: Vec<&str> = kernel
            .inner
            .wake_sources
            .iter()
            .filter(|s| s.cron_expression().is_some())
            .map(|s| s.name())
            .collect();
        assert_eq!(names, ["mine"]);
    }

    /// A sleeper on a cron wake no registered source covers (spec 3.2 §7.4, §8.1 `wake
    /// --cron`), on a manual clock: the kernel fires it at each occurrence — the first
    /// sleeper, then the successor it re-armed — and forgets the expression once the
    /// series is killed.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn a_cron_sleeper_wakes_at_each_occurrence_until_it_is_killed() {
        use adk_core::{Llm, ManualClock, RunState};
        use adk_model::{ScriptedLlm, ScriptedResponse};

        let clock = ManualClock::new(chrono::Utc::now());
        let runs: Arc<dyn DurableRunStore> =
            Arc::new(InMemoryRunStore::new().with_clock(Arc::new(clock.clone())));
        let model = Arc::new(ScriptedLlm::new(
            "scripted",
            ["first occurrence", "second occurrence"].map(ScriptedResponse::text),
        ));
        let agent = adk_agent::LlmAgentBuilder::new("agent")
            .model(Arc::clone(&model) as Arc<dyn Llm>)
            .build()
            .unwrap();
        let runner = Arc::new(
            Runner::builder()
                .app_name("adk-rust")
                .agent(Arc::new(agent))
                .session_service(Arc::new(adk_session::InMemorySessionService::new()))
                .build()
                .unwrap(),
        );
        let kernel = Kernel::builder()
            .config(
                KernelConfig::default()
                    .with_scheduler_tick(Duration::from_millis(50))
                    .with_clock(Arc::new(clock.clone()))
                    .with_control(ControlPlaneConfig::default().without_socket()),
            )
            .run_store(Arc::clone(&runs))
            .agent("adk-rust", runner)
            .build()
            .unwrap();
        kernel.start().await.unwrap();
        let hourly = "0 0 * * * *";
        let wake = WakeSet::any_of([Wake::Cron {
            expr: hourly.into(),
            missed: adk_core::MissedFirePolicy::Skip,
        }]);
        let run =
            NewRun::new("background", "adk-rust", "alice", "adk-rust", json!({ "text": "x" }));
        let first = kernel
            .processes()
            .spawn(run, ProcessSpec::new(ProcessKind::Scheduled).with_wake(wake.clone()))
            .await
            .unwrap()
            .meta
            .pid;
        let state = |pid: String| {
            let runs = Arc::clone(&runs);
            async move { runs.get(&pid).await.unwrap().map(|run| run.state) }
        };
        let wait_for = |what: &'static str, pid: String, wanted: RunState| async move {
            let started = tokio::time::Instant::now();
            while state(pid.clone()).await != Some(wanted) {
                assert!(started.elapsed() < Duration::from_secs(5), "timed out waiting for {what}");
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        };
        let successor = |parent: String| {
            let kernel = kernel.clone();
            async move {
                let started = tokio::time::Instant::now();
                loop {
                    let processes = kernel.processes().ps(ProcessFilter::default()).await.unwrap();
                    if let Some(next) =
                        processes.iter().find(|p| p.meta.parent.as_deref() == Some(parent.as_str()))
                    {
                        return next.meta.pid.clone();
                    }
                    assert!(
                        started.elapsed() < Duration::from_secs(5),
                        "timed out waiting for the successor of {parent}"
                    );
                    tokio::time::sleep(Duration::from_millis(20)).await;
                }
            }
        };
        wait_for("the sleeper asleep", first.clone(), RunState::Waiting).await;
        eventually("the expression to be fired by the kernel", || {
            kernel.inner.sup.watched_crons() == [hourly]
        })
        .await;
        assert_eq!(model.requests().len(), 0, "asleep until the hour");

        // Each hour is routed a second after it is due: a `skip` wake fires on time only.
        let spec = adk_core::ScheduleSpec::Cron { expr: hourly.into(), timezone: "UTC".into() };
        let first_hour = spec.next_after(clock.now()).unwrap().unwrap();
        clock.set(first_hour + chrono::Duration::seconds(1));
        wait_for("the first occurrence's run", first.clone(), RunState::Completed).await;
        let second = successor(first.clone()).await;
        wait_for("the successor asleep", second.clone(), RunState::Waiting).await;
        let meta = kernel.processes().get(&second).await.unwrap().unwrap().meta;
        assert_eq!(meta.wake, Some(wake.clone()), "the successor sleeps on the same cron wake");

        clock.set(spec.next_after(first_hour).unwrap().unwrap() + chrono::Duration::seconds(1));
        wait_for("the second occurrence's run", second.clone(), RunState::Completed).await;
        assert_eq!(model.requests().len(), 2, "one run per occurrence");
        let third = successor(second).await;
        wait_for("the next successor asleep", third.clone(), RunState::Waiting).await;

        kernel.processes().kill(&third, "the series ends").await.unwrap();
        eventually("the expression to be dropped", || kernel.inner.sup.watched_crons().is_empty())
            .await;
        tokio::time::sleep(Duration::from_millis(300)).await;
        let processes = kernel.processes().ps(ProcessFilter::default()).await.unwrap();
        assert!(
            !processes.iter().any(|p| p.meta.parent.as_deref() == Some(third.as_str())),
            "a killed sleeper is not re-armed"
        );
        kernel.stop().await.unwrap();
    }

    /// A cron sleeper run now (spec 3.2 §7.4 parity): refused while frozen, queued once per
    /// request id, woken with a wake reason that says so, re-armed on the same cron wake, and
    /// the expression's watermark untouched; the next tick is jittered: submitted at its
    /// scheduled time and keyed by it, routed only after the offset. A standing cron trigger
    /// runs now too, and a name no cron trigger has is refused.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn a_cron_sleeper_runs_now_and_its_next_tick_waits_out_the_jitter() {
        use adk_core::schedule::{Jitter, ScheduleSpec};
        use adk_core::{Llm, ManualClock, RunFilter, RunState};
        use adk_model::{ScriptedLlm, ScriptedResponse};

        let clock = ManualClock::new(
            chrono::DateTime::parse_from_rfc3339("2026-11-18T09:10:00Z").unwrap().into(),
        );
        let runs: Arc<dyn DurableRunStore> =
            Arc::new(InMemoryRunStore::new().with_clock(Arc::new(clock.clone())));
        let model = Arc::new(ScriptedLlm::new(
            "scripted",
            ["ran now", "the hourly tick", "the trigger now"].map(ScriptedResponse::text),
        ));
        let agent = adk_agent::LlmAgentBuilder::new("agent")
            .model(Arc::clone(&model) as Arc<dyn Llm>)
            .build()
            .unwrap();
        let runner = Arc::new(
            Runner::builder()
                .app_name("adk-rust")
                .agent(Arc::new(agent))
                .session_service(Arc::new(adk_session::InMemorySessionService::new()))
                .build()
                .unwrap(),
        );
        let jitter = Jitter::new(50, Duration::from_secs(3600));
        let yearly = "0 0 0 1 1 *";
        let kernel = Kernel::builder()
            .config(
                KernelConfig::default()
                    .with_scheduler_tick(Duration::from_millis(50))
                    .with_clock(Arc::new(clock.clone()))
                    .with_cron_jitter(jitter)
                    .with_control(ControlPlaneConfig::default().without_socket()),
            )
            .run_store(Arc::clone(&runs))
            .agent("adk-rust", runner)
            .trigger(Trigger::new(
                "digest",
                Wake::Cron { expr: yearly.into(), missed: adk_core::MissedFirePolicy::Skip },
                NewRun::new("background", "adk-rust", "alice", "adk-rust", json!({ "text": "d" })),
            ))
            .build()
            .unwrap();
        kernel.start().await.unwrap();
        let hourly = "0 0 * * * *";
        let wake = WakeSet::any_of([Wake::Cron {
            expr: hourly.into(),
            missed: adk_core::MissedFirePolicy::Skip,
        }]);
        let run =
            NewRun::new("background", "adk-rust", "alice", "adk-rust", json!({ "text": "x" }));
        let first = kernel
            .processes()
            .spawn(run, ProcessSpec::new(ProcessKind::Scheduled).with_wake(wake.clone()))
            .await
            .unwrap()
            .meta
            .pid;
        let state = |pid: String| {
            let runs = Arc::clone(&runs);
            async move { runs.get(&pid).await.unwrap().map(|run| run.state) }
        };
        let wait_for = |what: &'static str, pid: String, wanted: RunState| async move {
            let started = tokio::time::Instant::now();
            while state(pid.clone()).await != Some(wanted) {
                assert!(started.elapsed() < Duration::from_secs(5), "timed out waiting for {what}");
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        };
        wait_for("the sleeper asleep", first.clone(), RunState::Waiting).await;
        eventually("the expression to be fired by the kernel", || {
            kernel.inner.sup.watched_crons() == [hourly]
        })
        .await;
        let source = format!("kernel:{hourly}");
        let watermark = || async { kernel.inner.sup.watermarks.read(&source).await.unwrap() };
        let cursor = watermark().await;

        let target = || RunNowTarget::Process { pid: first.clone() };
        kernel.freeze("incident", AuditActor::default()).await.unwrap();
        let refused = kernel.run_now(target(), Some("r-1"), AuditActor::default()).await;
        assert!(matches!(refused, Err(KernelError::Frozen { .. })), "{refused:?}");
        kernel.unfreeze(AuditActor::default()).await.unwrap();

        let queued = kernel.run_now(target(), Some("r-1"), AuditActor::default()).await.unwrap();
        assert_eq!(
            (queued.key.as_str(), queued.existing),
            (format!("now:{first}:r-1").as_str(), false)
        );
        let again = kernel.run_now(target(), Some("r-1"), AuditActor::default()).await.unwrap();
        assert!(
            again.existing && again.wake_run_id == queued.wake_run_id,
            "one wake per request id"
        );
        wait_for("the run now", first.clone(), RunState::Completed).await;
        let reason = crate::WakeReason::recorded(
            &kernel.processes().get(&first).await.unwrap().unwrap().meta,
        )
        .expect("the run now records its wake reason");
        assert_eq!(reason.source, crate::wake::RUN_NOW_SOURCE);
        assert!(reason.payload.contains(r#""run_now":true"#), "{}", reason.payload);
        assert_eq!(watermark().await, cursor, "a run now moves no watermark");
        let second = loop {
            let processes = kernel.processes().ps(ProcessFilter::default()).await.unwrap();
            if let Some(next) =
                processes.iter().find(|p| p.meta.parent.as_deref() == Some(first.as_str()))
            {
                break next.meta.pid.clone();
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        };
        wait_for("the successor asleep", second.clone(), RunState::Waiting).await;
        assert_eq!(
            kernel.processes().get(&second).await.unwrap().unwrap().meta.wake,
            Some(wake.clone()),
            "the successor sleeps on the same cron wake"
        );
        let refused = kernel
            .run_now(RunNowTarget::Process { pid: "missing".into() }, None, AuditActor::default())
            .await;
        assert!(matches!(refused, Err(KernelError::NotFound { .. })), "{refused:?}");

        // The 10:00 tick is submitted when it falls due, keyed by 10:00, and waits out its
        // offset before it is routed.
        let ten = chrono::DateTime::parse_from_rfc3339("2026-11-18T10:00:00Z").unwrap().into();
        let spec = ScheduleSpec::Cron { expr: hourly.into(), timezone: "UTC".into() };
        let offset = jitter.salted("adk-rust").offset_in(&spec, &source, ten);
        assert!(offset < Duration::from_secs(30 * 60), "under half the hour: {offset:?}");
        clock.set(ten + chrono::Duration::seconds(1));
        let key = crate::wake::keys::cron(&source, ten);
        let wake_run = loop {
            let found = runs
                .list(RunFilter::default())
                .await
                .unwrap()
                .into_iter()
                .find(|run| run.idempotency_key.as_deref() == Some(key.as_str()));
            if let Some(found) = found {
                break found;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        };
        if offset >= Duration::from_secs(2) {
            assert_eq!(
                wake_run.not_before,
                Some(ten + chrono::Duration::from_std(offset).unwrap())
            );
            tokio::time::sleep(Duration::from_millis(300)).await;
            assert_eq!(
                state(second.clone()).await,
                Some(RunState::Waiting),
                "not before the offset"
            );
        }
        clock.set(ten + chrono::Duration::from_std(offset).unwrap() + chrono::Duration::seconds(1));
        wait_for("the jittered tick's run", second.clone(), RunState::Completed).await;
        assert_eq!(model.requests().len(), 2, "the run now and the tick");

        let refused = kernel
            .run_now(RunNowTarget::Trigger { name: "nope".into() }, None, AuditActor::default())
            .await;
        assert!(matches!(refused, Err(KernelError::Config { .. })), "{refused:?}");
        kernel
            .run_now(
                RunNowTarget::Trigger { name: "digest".into() },
                Some("t-1"),
                AuditActor::default(),
            )
            .await
            .unwrap();
        let started = tokio::time::Instant::now();
        loop {
            let processes = kernel.processes().ps(ProcessFilter::default()).await.unwrap();
            let fired = processes.iter().find(|p| {
                p.meta.kind == ProcessKind::Triggered { source: "digest".into() }
                    && p.run.state == RunState::Completed
            });
            if fired.is_some() {
                break;
            }
            assert!(started.elapsed() < Duration::from_secs(5), "the trigger did not run now");
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        assert_eq!(model.requests().len(), 3, "and the trigger run now");
        kernel.stop().await.unwrap();
    }
}