stateknot-store-postgres 0.1.0-alpha.1

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

use std::{fmt, time::Duration};

use serde::{Deserialize, Serialize};
use stateknot_core::{
    AgentAdmission, ArtifactRef, Checkpoint, CheckpointHead, CheckpointId, CompiledGraph,
    DeliveryFence, Digest, DurableTimer, DurableTimerRecord, DurableWait, FencingEpoch,
    InterruptRecord, InterruptRequest, JournalEvent, JournalExpectation, JournalHead,
    JournalPayload, ModelInvocation, NodeAttempt, OutboxAttempt, OutboxAttemptCompletion,
    OutboxAttemptStart, OutboxDelivery, OutboxDestinationRef, PendingNodeResult,
    PendingNodeResultHead, QuarantineId, RunFence, RunId, RunLease, RunLifecycle, RunRevision,
    RunTransition, SchedulerReservationId, SchedulerShardId, Superstep, TenantId, Timestamp,
    ToolInvocation,
};

use crate::StoreError;

const SCHEDULER_FAIRNESS_POLICY_DIGEST_DOMAIN: &[u8] = b"stateknot.scheduler-fairness-policy.v1\0";

/// Private storage coordinates for one immutable artifact object.
///
/// This value belongs only inside trusted storage providers. It must never be
/// serialized into an [`ArtifactRef`], returned through an Agent protocol, or
/// accepted as authorization. `Debug` deliberately omits every coordinate.
#[derive(Clone, Eq, PartialEq)]
pub struct ArtifactStorageLocator {
    storage_namespace: Box<str>,
    object_key: Box<str>,
    object_version: Option<Box<str>>,
    object_etag: Option<Box<str>>,
}

impl ArtifactStorageLocator {
    /// Maximum byte length of a deployment-owned storage namespace.
    pub const MAX_STORAGE_NAMESPACE_BYTES: usize = 128;
    /// Maximum UTF-8 byte length of a provider object key.
    pub const MAX_OBJECT_KEY_BYTES: usize = 1024;
    /// Maximum byte length of an opaque provider object version.
    pub const MAX_OBJECT_VERSION_BYTES: usize = 1024;
    /// Maximum byte length of an opaque provider entity tag.
    pub const MAX_OBJECT_ETAG_BYTES: usize = 1024;

    /// Validates private, provider-neutral object coordinates.
    ///
    /// The namespace is a non-secret deployment identifier, not a bucket name
    /// or endpoint. Object keys are relative and reject control characters,
    /// backslashes, empty segments, and traversal-like segments so the same
    /// locator remains safe across S3-compatible and in-memory backends.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidArtifactStorageLocator`] when any value is
    /// empty, oversized, contains a forbidden byte, or is path-like.
    pub fn new(
        storage_namespace: impl Into<String>,
        object_key: impl Into<String>,
        object_version: Option<String>,
        object_etag: Option<String>,
    ) -> Result<Self, StoreError> {
        let storage_namespace = storage_namespace.into();
        let object_key = object_key.into();
        validate_storage_namespace(&storage_namespace)?;
        validate_object_key(&object_key)?;
        let object_version =
            validate_opaque_locator_value(object_version, Self::MAX_OBJECT_VERSION_BYTES)?;
        let object_etag = validate_opaque_locator_value(object_etag, Self::MAX_OBJECT_ETAG_BYTES)?;
        Ok(Self {
            storage_namespace: storage_namespace.into_boxed_str(),
            object_key: object_key.into_boxed_str(),
            object_version,
            object_etag,
        })
    }

    /// Returns the deployment-owned storage namespace.
    #[must_use]
    pub fn storage_namespace(&self) -> &str {
        &self.storage_namespace
    }

    /// Returns the private relative object key.
    #[must_use]
    pub fn object_key(&self) -> &str {
        &self.object_key
    }

    /// Returns the optional immutable provider version identifier.
    #[must_use]
    pub fn object_version(&self) -> Option<&str> {
        self.object_version.as_deref()
    }

    /// Returns the optional provider entity tag captured after upload.
    #[must_use]
    pub fn object_etag(&self) -> Option<&str> {
        self.object_etag.as_deref()
    }
}

impl fmt::Debug for ArtifactStorageLocator {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ArtifactStorageLocator")
            .field("coordinates", &"<redacted>")
            .field("has_object_version", &self.object_version.is_some())
            .field("has_object_etag", &self.object_etag.is_some())
            .finish_non_exhaustive()
    }
}

/// Exact immutable input for one idempotent artifact registration.
#[derive(Clone, Eq, PartialEq)]
pub struct ArtifactRegistration {
    registration_key: Digest,
    artifact: ArtifactRef,
    locator: ArtifactStorageLocator,
}

impl ArtifactRegistration {
    /// Constructs an exact registry write intent.
    #[must_use]
    pub const fn new(
        registration_key: Digest,
        artifact: ArtifactRef,
        locator: ArtifactStorageLocator,
    ) -> Self {
        Self {
            registration_key,
            artifact,
            locator,
        }
    }

    /// Returns the caller's domain-separated idempotency digest.
    #[must_use]
    pub const fn registration_key(&self) -> Digest {
        self.registration_key
    }

    /// Returns the public immutable artifact metadata.
    #[must_use]
    pub const fn artifact(&self) -> &ArtifactRef {
        &self.artifact
    }

    /// Returns private object coordinates for the trusted provider.
    #[must_use]
    pub const fn locator(&self) -> &ArtifactStorageLocator {
        &self.locator
    }
}

impl fmt::Debug for ArtifactRegistration {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ArtifactRegistration")
            .field("identity", self.artifact.identity())
            .field("locator", &self.locator)
            .finish_non_exhaustive()
    }
}

/// Fully verified immutable artifact registry record.
#[derive(Clone, Eq, PartialEq)]
pub struct StoredArtifact {
    pub(crate) registration: ArtifactRegistration,
    pub(crate) registered_at: Timestamp,
}

impl StoredArtifact {
    /// Constructs a verified registry result for a custom registry provider.
    ///
    /// Custom implementations are responsible for returning this value only
    /// after enforcing the same immutable, tenant, lineage, and idempotency
    /// guarantees as `PostgresStore`.
    #[must_use]
    pub const fn new(registration: ArtifactRegistration, registered_at: Timestamp) -> Self {
        Self {
            registration,
            registered_at,
        }
    }

    /// Returns the exact immutable registration.
    #[must_use]
    pub const fn registration(&self) -> &ArtifactRegistration {
        &self.registration
    }

    /// Returns the public artifact reference.
    #[must_use]
    pub const fn artifact(&self) -> &ArtifactRef {
        self.registration.artifact()
    }

    /// Returns private object coordinates for the trusted provider.
    #[must_use]
    pub const fn locator(&self) -> &ArtifactStorageLocator {
        self.registration.locator()
    }

    /// Returns the database-clock registration observation.
    #[must_use]
    pub const fn registered_at(&self) -> Timestamp {
        self.registered_at
    }
}

impl fmt::Debug for StoredArtifact {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("StoredArtifact")
            .field("identity", self.artifact().identity())
            .field("registered_at", &self.registered_at)
            .field("locator", self.locator())
            .finish_non_exhaustive()
    }
}

/// Result of idempotently registering one immutable artifact and its locator.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ArtifactRegistrationOutcome {
    /// A new registry record committed.
    Registered(StoredArtifact),
    /// The exact record was already committed by an earlier attempt.
    Idempotent(StoredArtifact),
}

impl ArtifactRegistrationOutcome {
    /// Returns the fully verified durable record.
    #[must_use]
    pub const fn stored(&self) -> &StoredArtifact {
        match self {
            Self::Registered(stored) | Self::Idempotent(stored) => stored,
        }
    }
}

fn validate_storage_namespace(value: &str) -> Result<(), StoreError> {
    if value.is_empty()
        || value.len() > ArtifactStorageLocator::MAX_STORAGE_NAMESPACE_BYTES
        || value == "."
        || value == ".."
        || !value.as_bytes()[0].is_ascii_alphanumeric()
        || value
            .bytes()
            .any(|byte| !byte.is_ascii_alphanumeric() && !matches!(byte, b'.' | b'_' | b':' | b'-'))
    {
        return Err(StoreError::InvalidArtifactStorageLocator);
    }
    Ok(())
}

fn validate_object_key(value: &str) -> Result<(), StoreError> {
    if value.is_empty()
        || value.len() > ArtifactStorageLocator::MAX_OBJECT_KEY_BYTES
        || value.starts_with('/')
        || value.ends_with('/')
        || value.chars().any(|character| {
            character == '\\'
                || character.is_control()
                || matches!(character, '\u{FDD0}'..='\u{FDEF}')
                || (character as u32 & 0xFFFE) == 0xFFFE
        })
        || value
            .split('/')
            .any(|segment| segment.is_empty() || matches!(segment, "." | ".."))
    {
        return Err(StoreError::InvalidArtifactStorageLocator);
    }
    Ok(())
}

fn validate_opaque_locator_value(
    value: Option<String>,
    maximum_bytes: usize,
) -> Result<Option<Box<str>>, StoreError> {
    value
        .map(|value| {
            if value.is_empty()
                || value.len() > maximum_bytes
                || !value
                    .bytes()
                    .all(|byte| byte.is_ascii_graphic() || byte == b' ')
            {
                return Err(StoreError::InvalidArtifactStorageLocator);
            }
            Ok(value.into_boxed_str())
        })
        .transpose()
}

/// Immutable canonical policy bytes registered for one scheduler shard.
///
/// The store deliberately treats the policy body as opaque canonical bytes;
/// `stateknot-runtime` owns the weighted-schedule schema and verifies it before
/// registration and after loading. The domain-separated digest prevents policy
/// bytes from being substituted with another digest-bearing record type.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SchedulerFairnessPolicyRegistration {
    shard_id: SchedulerShardId,
    policy_digest: Digest,
    policy_bytes: Box<[u8]>,
    cycle_length: u16,
}

impl SchedulerFairnessPolicyRegistration {
    /// Maximum canonical policy byte length accepted by the provider.
    pub const MAX_POLICY_BYTES: usize = 262_144;
    /// Maximum number of deterministic slots in one weighted cycle.
    pub const MAX_CYCLE_LENGTH: u16 = 4096;

    /// Constructs and checksums one immutable shard policy registration.
    ///
    /// # Errors
    ///
    /// Rejects empty/oversized policy bytes or a zero/excessive cycle length.
    pub fn new(
        shard_id: SchedulerShardId,
        policy_bytes: impl Into<Vec<u8>>,
        cycle_length: u16,
    ) -> Result<Self, StoreError> {
        let policy_bytes = policy_bytes.into();
        if policy_bytes.is_empty()
            || policy_bytes.len() > Self::MAX_POLICY_BYTES
            || cycle_length == 0
            || cycle_length > Self::MAX_CYCLE_LENGTH
        {
            return Err(StoreError::InvalidSchedulerFairnessPolicy);
        }
        let mut preimage =
            Vec::with_capacity(SCHEDULER_FAIRNESS_POLICY_DIGEST_DOMAIN.len() + policy_bytes.len());
        preimage.extend_from_slice(SCHEDULER_FAIRNESS_POLICY_DIGEST_DOMAIN);
        preimage.extend_from_slice(&policy_bytes);
        Ok(Self {
            shard_id,
            policy_digest: Digest::sha256(preimage),
            policy_bytes: policy_bytes.into_boxed_slice(),
            cycle_length,
        })
    }

    /// Returns the immutable distributed-scheduler shard identity.
    #[must_use]
    pub const fn shard_id(&self) -> &SchedulerShardId {
        &self.shard_id
    }

    /// Returns the domain-separated canonical policy checksum.
    #[must_use]
    pub const fn policy_digest(&self) -> Digest {
        self.policy_digest
    }

    /// Returns the canonical runtime policy bytes.
    #[must_use]
    pub const fn policy_bytes(&self) -> &[u8] {
        &self.policy_bytes
    }

    /// Returns the exact number of slots in one weighted cycle.
    #[must_use]
    pub const fn cycle_length(&self) -> u16 {
        self.cycle_length
    }
}

/// Fully verified durable scheduler fairness policy snapshot.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StoredSchedulerFairnessPolicy {
    pub(crate) registration: SchedulerFairnessPolicyRegistration,
    pub(crate) registered_at: Timestamp,
}

impl StoredSchedulerFairnessPolicy {
    /// Returns the immutable registration payload.
    #[must_use]
    pub const fn registration(&self) -> &SchedulerFairnessPolicyRegistration {
        &self.registration
    }

    /// Returns the database clock at first registration.
    #[must_use]
    pub const fn registered_at(&self) -> Timestamp {
        self.registered_at
    }
}

/// Result of registering one immutable scheduler fairness shard.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SchedulerFairnessPolicyRegistrationOutcome {
    /// A new policy and global cursor committed.
    Registered(StoredSchedulerFairnessPolicy),
    /// The exact policy was already registered.
    Idempotent(StoredSchedulerFairnessPolicy),
}

impl SchedulerFairnessPolicyRegistrationOutcome {
    /// Returns the verified durable policy in either outcome.
    #[must_use]
    pub const fn policy(&self) -> &StoredSchedulerFairnessPolicy {
        match self {
            Self::Registered(policy) | Self::Idempotent(policy) => policy,
        }
    }
}

/// One globally ordered, lost-acknowledgement-safe fairness slot reservation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SchedulerFairnessReservation {
    pub(crate) shard_id: SchedulerShardId,
    pub(crate) reservation_id: SchedulerReservationId,
    pub(crate) policy_digest: Digest,
    pub(crate) sequence: u64,
    pub(crate) slot: u16,
    pub(crate) reserved_at: Timestamp,
}

impl SchedulerFairnessReservation {
    /// Returns the immutable scheduler shard.
    #[must_use]
    pub const fn shard_id(&self) -> &SchedulerShardId {
        &self.shard_id
    }

    /// Returns the stable idempotency identity supplied by the worker.
    #[must_use]
    pub const fn reservation_id(&self) -> SchedulerReservationId {
        self.reservation_id
    }

    /// Returns the immutable policy snapshot used for selection.
    #[must_use]
    pub const fn policy_digest(&self) -> Digest {
        self.policy_digest
    }

    /// Returns the zero-based global reservation sequence.
    #[must_use]
    pub const fn sequence(&self) -> u64 {
        self.sequence
    }

    /// Returns the zero-based slot within the weighted policy cycle.
    #[must_use]
    pub const fn slot(&self) -> u16 {
        self.slot
    }

    /// Returns the database time at first reservation.
    #[must_use]
    pub const fn reserved_at(&self) -> Timestamp {
        self.reserved_at
    }
}

/// Bounded maintenance policy for durable fairness reservation evidence.
///
/// A deployment must stop retrying a reservation identity before `retain_for`
/// elapses. Deleting an identity and retrying it later would legitimately
/// allocate a new slot, so the hard minimum provides an operational safety
/// margin above the runtime's bounded immediate retry loop.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SchedulerFairnessRetentionPolicy {
    retain_for: Duration,
    batch_size: u16,
}

impl SchedulerFairnessRetentionPolicy {
    /// Smallest supported evidence retention window.
    pub const MIN_RETAIN_FOR: Duration = Duration::from_secs(60 * 60);
    /// Largest supported evidence retention window.
    pub const MAX_RETAIN_FOR: Duration = Duration::from_secs(366 * 24 * 60 * 60);
    /// Largest row count deleted by one short transaction.
    pub const MAX_BATCH_SIZE: u16 = 10_000;

    /// Constructs one bounded retention policy.
    ///
    /// # Errors
    ///
    /// Rejects retention outside the hard window or a zero/excessive batch.
    pub const fn new(retain_for: Duration, batch_size: u16) -> Result<Self, StoreError> {
        if retain_for.as_nanos() < Self::MIN_RETAIN_FOR.as_nanos()
            || retain_for.as_nanos() > Self::MAX_RETAIN_FOR.as_nanos()
            || batch_size == 0
            || batch_size > Self::MAX_BATCH_SIZE
        {
            return Err(StoreError::InvalidSchedulerFairnessRetention);
        }
        Ok(Self {
            retain_for,
            batch_size,
        })
    }

    /// Returns the minimum age of evidence eligible for deletion.
    #[must_use]
    pub const fn retain_for(self) -> Duration {
        self.retain_for
    }

    /// Returns the maximum rows deleted by one transaction.
    #[must_use]
    pub const fn batch_size(self) -> u16 {
        self.batch_size
    }
}

/// Auditable result of one bounded fairness-reservation retention pass.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SchedulerFairnessRetentionReport {
    pub(crate) observed_at: Timestamp,
    pub(crate) cutoff: Timestamp,
    pub(crate) deleted: u16,
}

impl SchedulerFairnessRetentionReport {
    /// Returns the authoritative database clock for this maintenance pass.
    #[must_use]
    pub const fn observed_at(self) -> Timestamp {
        self.observed_at
    }

    /// Returns the exclusive oldest-retained cutoff.
    #[must_use]
    pub const fn cutoff(self) -> Timestamp {
        self.cutoff
    }

    /// Returns the exact number of deleted reservations.
    #[must_use]
    pub const fn deleted(self) -> u16 {
        self.deleted
    }
}

/// Fully validated immutable graph definition in one tenant registry.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StoredGraphDefinition {
    pub(crate) tenant_id: TenantId,
    pub(crate) graph: CompiledGraph,
    pub(crate) registered_at: Timestamp,
}

impl StoredGraphDefinition {
    /// Returns the tenant registry that owns this durable registration.
    #[must_use]
    pub const fn tenant_id(&self) -> &TenantId {
        &self.tenant_id
    }

    /// Returns the fully recompiled and integrity-checked graph definition.
    #[must_use]
    pub const fn graph(&self) -> &CompiledGraph {
        &self.graph
    }

    /// Returns the database-clock registration observation.
    #[must_use]
    pub const fn registered_at(&self) -> Timestamp {
        self.registered_at
    }
}

/// Result of idempotently registering one immutable compiled graph version.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GraphDefinitionRegistrationOutcome {
    /// A new owner-qualified graph version committed.
    Registered(StoredGraphDefinition),
    /// The exact canonical graph definition was already registered.
    Idempotent(StoredGraphDefinition),
}

impl GraphDefinitionRegistrationOutcome {
    /// Returns the fully validated durable graph definition.
    #[must_use]
    pub const fn definition(&self) -> &StoredGraphDefinition {
        match self {
            Self::Registered(definition) | Self::Idempotent(definition) => definition,
        }
    }
}

/// Closed reason taxonomy for stopping all execution of one durable run.
///
/// The caller stores only a stable component code and an integrity digest; raw
/// payloads, credentials, SQL, and private error text are intentionally outside
/// this record.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RunQuarantineCause {
    /// Canonical bytes, digests, links, or immutable history failed validation.
    IntegrityFailure,
    /// A required durable schema or graph format is unsupported by this binary.
    UnsupportedSchema,
    /// Required integrity-bound external storage evidence is unavailable.
    MissingArtifact,
    /// A durable reference escaped its tenant boundary.
    CrossTenantReference,
    /// Authoritative history and a mutable projection disagree.
    ProjectionMismatch,
    /// No higher safe fencing epoch can be issued.
    FencingEpochExhausted,
    /// A trusted operator policy explicitly prohibited further execution.
    OperatorPolicy,
}

impl RunQuarantineCause {
    /// Returns the stable storage and metrics code.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::IntegrityFailure => "integrity_failure",
            Self::UnsupportedSchema => "unsupported_schema",
            Self::MissingArtifact => "missing_artifact",
            Self::CrossTenantReference => "cross_tenant_reference",
            Self::ProjectionMismatch => "projection_mismatch",
            Self::FencingEpochExhausted => "fencing_epoch_exhausted",
            Self::OperatorPolicy => "operator_policy",
        }
    }
}

/// Bounded non-secret machine code identifying the failed recovery component.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RunQuarantineComponent(Box<str>);

impl RunQuarantineComponent {
    /// Maximum encoded component-code length.
    pub const MAX_LEN: usize = 128;

    /// Validates a lowercase ASCII component code.
    ///
    /// Codes use `a-z`, `0-9`, `.`, `_`, `:`, and `-`. They are suitable for
    /// metrics and audit routing, not for user-controlled diagnostic text.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidRunQuarantineComponent`] when the code is
    /// empty, oversized, or outside the documented grammar.
    pub fn new(value: impl Into<String>) -> Result<Self, StoreError> {
        let value = value.into();
        if value.is_empty()
            || value.len() > Self::MAX_LEN
            || value.bytes().any(|byte| {
                !byte.is_ascii_lowercase()
                    && !byte.is_ascii_digit()
                    && !matches!(byte, b'.' | b'_' | b':' | b'-')
            })
        {
            return Err(StoreError::InvalidRunQuarantineComponent);
        }
        Ok(Self(value.into_boxed_str()))
    }

    /// Derives a stable `store.*` component from a payload-redacted corruption.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidRunQuarantineRequest`] when `error` is not
    /// [`StoreError::CorruptData`], or
    /// [`StoreError::InvalidRunQuarantineComponent`] if a future record category
    /// cannot fit the bounded component grammar.
    pub fn from_corrupt_store_error(error: &StoreError) -> Result<Self, StoreError> {
        let record = error
            .corrupt_record()
            .ok_or(StoreError::InvalidRunQuarantineRequest)?;
        let mut component = String::with_capacity("store.".len() + record.len());
        component.push_str("store.");
        let mut previous_separator = false;
        for byte in record.bytes() {
            let normalized = if byte.is_ascii_alphanumeric() {
                byte.to_ascii_lowercase()
            } else if matches!(byte, b'.' | b':' | b'-') {
                byte
            } else {
                b'_'
            };
            if normalized == b'_' {
                if previous_separator {
                    continue;
                }
                previous_separator = true;
            } else {
                previous_separator = false;
            }
            component.push(char::from(normalized));
        }
        while component.ends_with('_') {
            component.pop();
        }
        Self::new(component)
    }

    /// Returns the stable component code.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Immutable idempotency intent for quarantining one tenant-scoped run.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RunQuarantineRequest {
    pub(crate) tenant_id: TenantId,
    pub(crate) run_id: RunId,
    pub(crate) quarantine_id: QuarantineId,
    pub(crate) expectation: JournalExpectation,
    pub(crate) cause: RunQuarantineCause,
    pub(crate) component: RunQuarantineComponent,
    pub(crate) evidence_digest: Digest,
    pub(crate) expected_fence: Option<RunFence>,
}

impl RunQuarantineRequest {
    /// Constructs an exact, tenant-bound quarantine observation intent.
    ///
    /// `evidence_digest` identifies a caller-retained, redacted evidence bundle;
    /// evidence bytes are deliberately not copied into the operational store.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidRunQuarantineRequest`] when an exact journal
    /// expectation belongs to another tenant or run.
    pub fn new(
        tenant_id: TenantId,
        run_id: RunId,
        quarantine_id: QuarantineId,
        expectation: JournalExpectation,
        cause: RunQuarantineCause,
        component: RunQuarantineComponent,
        evidence_digest: Digest,
    ) -> Result<Self, StoreError> {
        if expectation
            .head()
            .is_some_and(|head| head.tenant_id() != &tenant_id || head.run_id() != run_id)
        {
            return Err(StoreError::InvalidRunQuarantineRequest);
        }
        Ok(Self {
            tenant_id,
            run_id,
            quarantine_id,
            expectation,
            cause,
            component,
            evidence_digest,
            expected_fence: None,
        })
    }

    /// Binds this observation to the exact live worker fence that detected it.
    ///
    /// A fenced quarantine commits only while that attempt and epoch still own
    /// an unexpired lease. This prevents a superseded or expired recovery worker
    /// from stopping a successor that happens to share the same journal head.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidRunQuarantineRequest`] when the fence
    /// crosses the request tenant or run.
    pub fn with_expected_fence(mut self, fence: RunFence) -> Result<Self, StoreError> {
        if fence.tenant_id() != &self.tenant_id || fence.run_id() != self.run_id {
            return Err(StoreError::InvalidRunQuarantineRequest);
        }
        if self
            .expected_fence
            .as_ref()
            .is_some_and(|expected| expected != &fence)
        {
            return Err(StoreError::InvalidRunQuarantineRequest);
        }
        self.expected_fence = Some(fence);
        Ok(self)
    }

    /// Returns the tenant boundary.
    #[must_use]
    pub const fn tenant_id(&self) -> &TenantId {
        &self.tenant_id
    }

    /// Returns the quarantined run identity.
    #[must_use]
    pub const fn run_id(&self) -> RunId {
        self.run_id
    }

    /// Returns the stable lost-acknowledgement identity.
    #[must_use]
    pub const fn quarantine_id(&self) -> QuarantineId {
        self.quarantine_id
    }

    /// Returns the exact journal observation that this evidence describes.
    #[must_use]
    pub const fn expectation(&self) -> &JournalExpectation {
        &self.expectation
    }

    /// Returns the closed quarantine cause.
    #[must_use]
    pub const fn cause(&self) -> RunQuarantineCause {
        self.cause
    }

    /// Returns the non-secret recovery component code.
    #[must_use]
    pub const fn component(&self) -> &RunQuarantineComponent {
        &self.component
    }

    /// Returns the caller-retained evidence checksum.
    #[must_use]
    pub const fn evidence_digest(&self) -> Digest {
        self.evidence_digest
    }

    /// Returns the exact recovery fence that must still own the run, if any.
    #[must_use]
    pub const fn expected_fence(&self) -> Option<&RunFence> {
        self.expected_fence.as_ref()
    }
}

/// Stable context for automatically quarantining one failed recovery read.
///
/// Clone and reuse the complete value after an ambiguous database outcome. The
/// eventual corruption category is derived from [`StoreError::CorruptData`]
/// rather than accepted from the caller.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CorruptionQuarantineContext {
    pub(crate) tenant_id: TenantId,
    pub(crate) run_id: RunId,
    pub(crate) quarantine_id: QuarantineId,
    pub(crate) expectation: JournalExpectation,
    pub(crate) evidence_digest: Digest,
    pub(crate) expected_fence: Option<RunFence>,
}

impl CorruptionQuarantineContext {
    /// Constructs a tenant-bound recovery observation.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidRunQuarantineRequest`] when an exact head
    /// belongs to another tenant or run.
    pub fn new(
        tenant_id: TenantId,
        run_id: RunId,
        quarantine_id: QuarantineId,
        expectation: JournalExpectation,
        evidence_digest: Digest,
    ) -> Result<Self, StoreError> {
        if expectation
            .head()
            .is_some_and(|head| head.tenant_id() != &tenant_id || head.run_id() != run_id)
        {
            return Err(StoreError::InvalidRunQuarantineRequest);
        }
        Ok(Self {
            tenant_id,
            run_id,
            quarantine_id,
            expectation,
            evidence_digest,
            expected_fence: None,
        })
    }

    /// Binds all corruption quarantines from this context to one live fence.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidClaimedRunRecoveryContext`] when the fence
    /// crosses the context tenant or run.
    pub fn with_expected_fence(mut self, fence: RunFence) -> Result<Self, StoreError> {
        if fence.tenant_id() != &self.tenant_id || fence.run_id() != self.run_id {
            return Err(StoreError::InvalidClaimedRunRecoveryContext);
        }
        if self
            .expected_fence
            .as_ref()
            .is_some_and(|expected| expected != &fence)
        {
            return Err(StoreError::InvalidClaimedRunRecoveryContext);
        }
        self.expected_fence = Some(fence);
        Ok(self)
    }

    /// Returns the tenant boundary.
    #[must_use]
    pub const fn tenant_id(&self) -> &TenantId {
        &self.tenant_id
    }

    /// Returns the observed run identity.
    #[must_use]
    pub const fn run_id(&self) -> RunId {
        self.run_id
    }

    /// Returns the stable quarantine identity.
    #[must_use]
    pub const fn quarantine_id(&self) -> QuarantineId {
        self.quarantine_id
    }

    /// Returns the exact journal observation made by recovery.
    #[must_use]
    pub const fn expectation(&self) -> &JournalExpectation {
        &self.expectation
    }

    /// Returns the caller-retained redacted evidence checksum.
    #[must_use]
    pub const fn evidence_digest(&self) -> Digest {
        self.evidence_digest
    }

    /// Returns the exact live fence required for quarantine, when bound.
    #[must_use]
    pub const fn expected_fence(&self) -> Option<&RunFence> {
        self.expected_fence.as_ref()
    }

    pub(crate) fn into_request(
        self,
        component: RunQuarantineComponent,
    ) -> Result<RunQuarantineRequest, StoreError> {
        let request = RunQuarantineRequest::new(
            self.tenant_id,
            self.run_id,
            self.quarantine_id,
            self.expectation,
            RunQuarantineCause::IntegrityFailure,
            component,
            self.evidence_digest,
        )?;
        match self.expected_fence {
            Some(fence) => request.with_expected_fence(fence),
            None => Ok(request),
        }
    }
}

/// Fully verified immutable quarantine observation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RunQuarantine {
    pub(crate) request: RunQuarantineRequest,
    pub(crate) quarantined_at: Timestamp,
    pub(crate) digest: Digest,
}

impl RunQuarantine {
    /// Returns the immutable quarantine request.
    #[must_use]
    pub const fn request(&self) -> &RunQuarantineRequest {
        &self.request
    }

    /// Returns the database-clock observation that removed the run from execution.
    #[must_use]
    pub const fn quarantined_at(&self) -> Timestamp {
        self.quarantined_at
    }

    /// Returns the canonical observation checksum.
    #[must_use]
    pub const fn digest(&self) -> Digest {
        self.digest
    }
}

/// Result of atomically recording evidence and removing a run from execution.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RunQuarantineCommitOutcome {
    /// New immutable evidence and the run quarantine projection committed.
    Committed(RunQuarantine),
    /// The exact stable request had already committed.
    Idempotent(RunQuarantine),
}

impl RunQuarantineCommitOutcome {
    /// Returns the fully verified durable quarantine observation.
    #[must_use]
    pub const fn quarantine(&self) -> &RunQuarantine {
        match self {
            Self::Committed(quarantine) | Self::Idempotent(quarantine) => quarantine,
        }
    }
}

/// Result of idempotent run admission.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum AdmissionOutcome {
    /// A new pending run row committed.
    Committed(RunLifecycle),
    /// The same provenance was already admitted; the current snapshot is returned.
    Idempotent(RunLifecycle),
}

impl AdmissionOutcome {
    /// Returns the validated lifecycle snapshot.
    #[must_use]
    pub const fn lifecycle(&self) -> &RunLifecycle {
        match self {
            Self::Committed(lifecycle) | Self::Idempotent(lifecycle) => lifecycle,
        }
    }
}

/// Fully verified durable Agent admission and its current run projection.
///
/// `event` and `checkpoint` are always the immutable sequence-one and
/// superstep-zero anchors. `run` is the current snapshot and may therefore have
/// advanced beyond both anchors when this value is returned by a retry or load.
#[derive(Clone, Debug)]
pub struct StoredAgentAdmission {
    pub(crate) admission: AgentAdmission,
    pub(crate) run: StoredRun,
    pub(crate) event: JournalEvent,
    pub(crate) checkpoint: Checkpoint,
}

impl StoredAgentAdmission {
    /// Returns the immutable database-clock admission snapshot.
    #[must_use]
    pub const fn admission(&self) -> &AgentAdmission {
        &self.admission
    }

    /// Returns the current validated run row.
    #[must_use]
    pub const fn run(&self) -> &StoredRun {
        &self.run
    }

    /// Returns the immutable first journal event.
    #[must_use]
    pub const fn event(&self) -> &JournalEvent {
        &self.event
    }

    /// Returns the immutable superstep-zero checkpoint.
    #[must_use]
    pub const fn checkpoint(&self) -> &Checkpoint {
        &self.checkpoint
    }
}

/// Result of atomically admitting and initializing one executable Agent run.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum AgentAdmissionCommitOutcome {
    /// The admission, run, event, lifecycle start, and checkpoint committed.
    Committed(StoredAgentAdmission),
    /// The exact immutable request had already committed.
    Idempotent(StoredAgentAdmission),
}

impl AgentAdmissionCommitOutcome {
    /// Returns the fully verified durable admission in either outcome.
    #[must_use]
    pub const fn stored(&self) -> &StoredAgentAdmission {
        match self {
            Self::Committed(stored) | Self::Idempotent(stored) => stored,
        }
    }
}

/// Fully verified tenant-scoped ingress idempotency mapping and Agent admission.
#[derive(Clone, Debug)]
pub struct StoredAgentSubmission {
    pub(crate) key_digest: Digest,
    pub(crate) submission_digest: Digest,
    pub(crate) admission: StoredAgentAdmission,
    pub(crate) created_at: Timestamp,
}

impl StoredAgentSubmission {
    /// Returns the tenant-scoped digest of the raw caller key.
    #[must_use]
    pub const fn key_digest(&self) -> Digest {
        self.key_digest
    }

    /// Returns the digest of caller-controlled submission content.
    #[must_use]
    pub const fn submission_digest(&self) -> Digest {
        self.submission_digest
    }

    /// Returns the exact durable Agent admission selected by this key.
    #[must_use]
    pub const fn admission(&self) -> &StoredAgentAdmission {
        &self.admission
    }

    /// Returns the database observation shared with the atomic admission.
    #[must_use]
    pub const fn created_at(&self) -> Timestamp {
        self.created_at
    }
}

/// Result of an ingress-keyed atomic Agent submission.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum AgentSubmissionCommitOutcome {
    /// A new key mapping committed with a new or exact retained Agent admission.
    Committed(StoredAgentSubmission),
    /// The same key and caller content already selected one durable run.
    Idempotent(StoredAgentSubmission),
}

impl AgentSubmissionCommitOutcome {
    /// Returns the fully verified mapping and admission in either outcome.
    #[must_use]
    pub const fn stored(&self) -> &StoredAgentSubmission {
        match self {
            Self::Committed(stored) | Self::Idempotent(stored) => stored,
        }
    }
}

/// Result of an idempotent journal append.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum AppendOutcome {
    /// A new event and projection committed atomically.
    Committed(JournalEvent),
    /// The identical event intent was already committed.
    Idempotent(JournalEvent),
}

/// Result of atomically committing a journal event and initial graph
/// checkpoint.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum CheckpointCommitOutcome {
    /// A new event, checkpoint, run head, and optional lifecycle projection committed.
    Committed {
        /// Newly committed journal event.
        event: JournalEvent,
        /// Newly committed immutable checkpoint.
        checkpoint: Checkpoint,
    },
    /// The exact event, projection, and checkpoint intent had already committed.
    Idempotent {
        /// Previously committed journal event.
        event: JournalEvent,
        /// Previously committed immutable checkpoint.
        checkpoint: Checkpoint,
    },
}

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

    /// Returns the validated immutable checkpoint.
    #[must_use]
    pub const fn checkpoint(&self) -> &Checkpoint {
        match self {
            Self::Committed { checkpoint, .. } | Self::Idempotent { checkpoint, .. } => checkpoint,
        }
    }
}

/// Result of atomically entering `waiting` with a checkpoint and complete
/// durable interrupt/timer registration set.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum WaitCheckpointCommitOutcome {
    /// The event, checkpoint, lifecycle projection, and registrations committed.
    Committed {
        /// Newly committed anchoring journal event.
        event: JournalEvent,
        /// Newly committed immutable checkpoint.
        checkpoint: Checkpoint,
        /// Complete materialized registration batch in semantic order.
        waits: Vec<DurableWait>,
    },
    /// The exact complete transaction had already committed.
    Idempotent {
        /// Previously committed anchoring journal event.
        event: JournalEvent,
        /// Previously committed immutable checkpoint.
        checkpoint: Checkpoint,
        /// Complete verified registration batch in semantic order.
        waits: Vec<DurableWait>,
    },
}

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

    /// Returns the immutable checkpoint committed at the wait barrier.
    #[must_use]
    pub const fn checkpoint(&self) -> &Checkpoint {
        match self {
            Self::Committed { checkpoint, .. } | Self::Idempotent { checkpoint, .. } => checkpoint,
        }
    }

    /// Returns every durable registration in lifecycle semantic order.
    #[must_use]
    pub fn waits(&self) -> &[DurableWait] {
        match self {
            Self::Committed { waits, .. } | Self::Idempotent { waits, .. } => waits,
        }
    }
}

/// Result of atomically resolving one exact durable interrupt.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum InterruptResolutionCommitOutcome {
    /// The event, resolution, lifecycle, and wait projection committed.
    Committed {
        /// Newly committed resolution event.
        event: JournalEvent,
        /// Complete immutable interrupt history.
        record: InterruptRecord,
    },
    /// The exact complete resolution transaction had already committed.
    Idempotent {
        /// Previously committed resolution event.
        event: JournalEvent,
        /// Complete verified interrupt history.
        record: InterruptRecord,
    },
}

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

    /// Returns the complete interrupt history.
    #[must_use]
    pub const fn record(&self) -> &InterruptRecord {
        match self {
            Self::Committed { record, .. } | Self::Idempotent { record, .. } => record,
        }
    }
}

/// Result of atomically firing one exact due durable timer.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum TimerFiringCommitOutcome {
    /// The event, firing, lifecycle, and wait projection committed.
    Committed {
        /// Newly committed firing event.
        event: JournalEvent,
        /// Complete immutable timer history.
        record: DurableTimerRecord,
    },
    /// The exact complete firing transaction had already committed.
    Idempotent {
        /// Previously committed firing event.
        event: JournalEvent,
        /// Complete verified timer history.
        record: DurableTimerRecord,
    },
}

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

    /// Returns the complete timer history.
    #[must_use]
    pub const fn record(&self) -> &DurableTimerRecord {
        match self {
            Self::Committed { record, .. } | Self::Idempotent { record, .. } => record,
        }
    }
}

/// Durable reason an outstanding wait was abandoned without resolution/firing.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum WaitAbandonmentReason {
    /// The run entered cooperative cancellation.
    RunCancellation,
    /// The run committed a terminal non-cancellation failure.
    RunFailure,
}

/// One integrity-bound audit fact for a wait abandoned by a run-level edge.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WaitAbandonment {
    pub(crate) wait: DurableWait,
    pub(crate) reason: WaitAbandonmentReason,
    pub(crate) journal: JournalHead,
    pub(crate) digest: Digest,
}

impl WaitAbandonment {
    /// Returns the immutable registration that was abandoned.
    #[must_use]
    pub const fn wait(&self) -> &DurableWait {
        &self.wait
    }

    /// Returns the run-level reason for abandonment.
    #[must_use]
    pub const fn reason(&self) -> WaitAbandonmentReason {
        self.reason
    }

    /// Returns the exact journal event that abandoned the wait.
    #[must_use]
    pub const fn journal(&self) -> &JournalHead {
        &self.journal
    }

    /// Returns the provider-domain integrity checksum.
    #[must_use]
    pub const fn digest(&self) -> Digest {
        self.digest
    }
}

/// Result of atomically cancelling/failing a waiting run and abandoning its
/// complete outstanding wait set.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum WaitAbandonmentCommitOutcome {
    /// The event, lifecycle edge, and every abandonment fact committed.
    Committed {
        /// Newly committed run-level event.
        event: JournalEvent,
        /// Complete abandoned set in deterministic registration identity order.
        abandonments: Vec<WaitAbandonment>,
    },
    /// The exact complete abandonment transaction had already committed.
    Idempotent {
        /// Previously committed run-level event.
        event: JournalEvent,
        /// Complete verified abandoned set.
        abandonments: Vec<WaitAbandonment>,
    },
}

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

    /// Returns every abandonment fact.
    #[must_use]
    pub fn abandonments(&self) -> &[WaitAbandonment] {
        match self {
            Self::Committed { abandonments, .. } | Self::Idempotent { abandonments, .. } => {
                abandonments
            }
        }
    }
}

/// Result of atomically consuming one complete result barrier and committing
/// its anchoring event and successor checkpoint.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum BarrierCommitOutcome {
    /// The event, successor checkpoint, and every result-consumption record
    /// committed in one transaction.
    Committed {
        /// Newly committed anchoring journal event.
        event: JournalEvent,
        /// Newly committed immutable successor checkpoint.
        checkpoint: Checkpoint,
    },
    /// The exact barrier transaction had already committed.
    Idempotent {
        /// Previously committed anchoring journal event.
        event: JournalEvent,
        /// Previously committed immutable successor checkpoint.
        checkpoint: Checkpoint,
    },
}

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

    /// Returns the validated immutable successor checkpoint.
    #[must_use]
    pub const fn checkpoint(&self) -> &Checkpoint {
        match self {
            Self::Committed { checkpoint, .. } | Self::Idempotent { checkpoint, .. } => checkpoint,
        }
    }
}

/// Result of atomically committing a journal event and tool invocation revision.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ToolInvocationCommitOutcome {
    /// A new event and immutable invocation revision committed atomically.
    Committed {
        /// Newly committed journal event.
        event: JournalEvent,
        /// Newly committed invocation revision.
        invocation: ToolInvocation,
    },
    /// The exact event and invocation mutation had already committed.
    Idempotent {
        /// Previously committed journal event.
        event: JournalEvent,
        /// Previously committed invocation revision.
        invocation: ToolInvocation,
    },
}

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

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

/// Result of atomically committing a journal event and model invocation revision.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ModelInvocationCommitOutcome {
    /// A new event and immutable invocation revision committed atomically.
    Committed {
        /// Newly committed journal event.
        event: JournalEvent,
        /// Newly committed invocation revision.
        invocation: ModelInvocation,
    },
    /// The exact event and invocation mutation had already committed.
    Idempotent {
        /// Previously committed journal event.
        event: JournalEvent,
        /// Previously committed invocation revision.
        invocation: ModelInvocation,
    },
}

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

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

/// Legacy outcome shape for the pre-v6 direct pending-result API.
///
/// New writes return [`NodeAttemptCommitOutcome`] because every result must be
/// owned by a durable physical node attempt. This type remains public so the
/// fail-closed compatibility method can preserve its original signature.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum PendingNodeResultCommitOutcome {
    /// A new event and immutable pending result committed atomically.
    Committed {
        /// Newly committed journal event.
        event: JournalEvent,
        /// Newly committed pending node result.
        result: PendingNodeResult,
    },
    /// The same semantic node result had already committed.
    Idempotent {
        /// Original journal event that anchored the stored winner.
        event: JournalEvent,
        /// Previously committed pending node result.
        result: PendingNodeResult,
    },
}

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

    /// Returns the validated immutable pending result.
    #[must_use]
    pub const fn result(&self) -> &PendingNodeResult {
        match self {
            Self::Committed { result, .. } | Self::Idempotent { result, .. } => result,
        }
    }
}

/// Result of atomically committing a node-attempt start or completion event.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum NodeAttemptCommitOutcome {
    /// A new event and immutable node-attempt record committed atomically.
    Committed {
        /// Newly committed anchoring journal event.
        event: JournalEvent,
        /// Fully restored attempt after this mutation.
        attempt: NodeAttempt,
    },
    /// The exact start or completion had already committed.
    Idempotent {
        /// Original journal event that anchored the stored mutation.
        event: JournalEvent,
        /// Fully restored durable attempt.
        attempt: NodeAttempt,
    },
}

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

    /// Returns the fully restored physical attempt.
    #[must_use]
    pub const fn attempt(&self) -> &NodeAttempt {
        match self {
            Self::Committed { attempt, .. } | Self::Idempotent { attempt, .. } => attempt,
        }
    }
}

/// Fully validated immutable destination snapshot used by dispatch adapters.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StoredOutboxDestination {
    pub(crate) destination: OutboxDestinationRef,
    pub(crate) config: JournalPayload,
    pub(crate) created_at: Timestamp,
}

impl StoredOutboxDestination {
    /// Returns the immutable destination identity and snapshot checksum.
    #[must_use]
    pub const fn destination(&self) -> &OutboxDestinationRef {
        &self.destination
    }

    /// Returns the canonical schema-pinned non-secret routing configuration.
    #[must_use]
    pub const fn config(&self) -> &JournalPayload {
        &self.config
    }

    /// Returns the database registration observation.
    #[must_use]
    pub const fn created_at(&self) -> Timestamp {
        self.created_at
    }
}

/// Result of idempotently registering one immutable destination snapshot.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum OutboxDestinationRegistrationOutcome {
    /// A new immutable destination snapshot committed.
    Registered(StoredOutboxDestination),
    /// The exact snapshot was already registered.
    Idempotent(StoredOutboxDestination),
}

impl OutboxDestinationRegistrationOutcome {
    /// Returns the validated immutable destination snapshot.
    #[must_use]
    pub const fn destination(&self) -> &StoredOutboxDestination {
        match self {
            Self::Registered(destination) | Self::Idempotent(destination) => destination,
        }
    }
}

/// Result of atomically appending one journal fact and its exact outbox set.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum OutboxEnqueueOutcome {
    /// The event and every requested delivery committed in one transaction.
    Committed {
        /// Newly committed journal event.
        event: JournalEvent,
        /// Immutable deliveries in caller order.
        deliveries: Vec<OutboxDelivery>,
    },
    /// The exact event and complete delivery set had already committed.
    Idempotent {
        /// Previously committed journal event.
        event: JournalEvent,
        /// Fully validated durable deliveries in caller order.
        deliveries: Vec<OutboxDelivery>,
    },
}

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

    /// Returns the complete immutable delivery set.
    #[must_use]
    pub fn deliveries(&self) -> &[OutboxDelivery] {
        match self {
            Self::Committed { deliveries, .. } | Self::Idempotent { deliveries, .. } => deliveries,
        }
    }
}

/// One atomically claimed delivery and its durable-before-dispatch start.
#[derive(Clone, Debug)]
pub struct OutboxClaim {
    pub(crate) destination: StoredOutboxDestination,
    pub(crate) delivery: OutboxDelivery,
    pub(crate) start: OutboxAttemptStart,
}

impl OutboxClaim {
    /// Returns the pinned destination snapshot needed by the adapter.
    #[must_use]
    pub const fn destination(&self) -> &StoredOutboxDestination {
        &self.destination
    }

    /// Returns the immutable delivery and protocol payload.
    #[must_use]
    pub const fn delivery(&self) -> &OutboxDelivery {
        &self.delivery
    }

    /// Returns the durable attempt start that must precede network I/O.
    #[must_use]
    pub const fn start(&self) -> &OutboxAttemptStart {
        &self.start
    }

    /// Returns the exact completion fence.
    #[must_use]
    pub const fn fence(&self) -> &DeliveryFence {
        self.start.fence()
    }
}

/// Result of an atomic tenant queue claim with a stable physical attempt ID.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum OutboxClaimOutcome {
    /// New ownership committed before dispatch may begin.
    Claimed(OutboxClaim),
    /// The same attempt ID had already claimed this exact delivery.
    Idempotent(OutboxClaim),
    /// No eligible unlocked delivery was visible at the database observation.
    NoWork,
}

impl OutboxClaimOutcome {
    /// Returns the claimed work, if any.
    #[must_use]
    pub const fn claim(&self) -> Option<&OutboxClaim> {
        match self {
            Self::Claimed(claim) | Self::Idempotent(claim) => Some(claim),
            Self::NoWork => None,
        }
    }
}

/// Result of idempotently committing one delivery-attempt completion.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum OutboxCompletionOutcome {
    /// A new immutable completion and projection update committed.
    Committed {
        /// Fully restored terminal physical attempt.
        attempt: OutboxAttempt,
    },
    /// The exact semantic completion had already committed.
    Idempotent {
        /// Fully restored terminal physical attempt.
        attempt: OutboxAttempt,
    },
}

impl OutboxCompletionOutcome {
    /// Returns the fully restored completed attempt.
    #[must_use]
    pub const fn attempt(&self) -> &OutboxAttempt {
        match self {
            Self::Committed { attempt } | Self::Idempotent { attempt } => attempt,
        }
    }

    /// Returns the immutable completion.
    #[must_use]
    pub const fn completion(&self) -> Option<&OutboxAttemptCompletion> {
        self.attempt().completion()
    }
}

/// Hard-bounded number of outbox attempts returned in one history page.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct OutboxAttemptHistoryPageSize(u8);

impl OutboxAttemptHistoryPageSize {
    /// Largest decoded page accepted by the provider.
    pub const MAX: u8 = 16;

    /// Constructs a positive bounded page size.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidOutboxAttemptPageSize`] outside `1..=16`.
    pub const fn new(value: u8) -> Result<Self, StoreError> {
        if value == 0 || value > Self::MAX {
            return Err(StoreError::InvalidOutboxAttemptPageSize);
        }
        Ok(Self(value))
    }

    /// Returns the page size as an integer.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

/// One bounded, fully verified ascending outbox-attempt history page.
#[derive(Clone, Debug)]
pub struct OutboxAttemptHistoryPage {
    pub(crate) records: Vec<OutboxAttempt>,
    pub(crate) has_more: bool,
}

impl OutboxAttemptHistoryPage {
    /// Returns immutable attempts in ascending fencing-epoch order.
    #[must_use]
    pub fn records(&self) -> &[OutboxAttempt] {
        &self.records
    }

    /// Returns whether a later attempt remains.
    #[must_use]
    pub const fn has_more(&self) -> bool {
        self.has_more
    }

    /// Returns the exact next-page cursor.
    #[must_use]
    pub fn next_cursor(&self) -> Option<OutboxAttempt> {
        self.records.last().cloned()
    }
}

/// Hard-bounded number of physical node attempts in one history page.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct NodeAttemptHistoryPageSize(u8);

impl NodeAttemptHistoryPageSize {
    /// Largest page accepted by the provider.
    ///
    /// A start and completion can occupy about 17 MiB together, so two
    /// records cap provider-owned decoded page memory near 34 MiB before
    /// driver overhead.
    pub const MAX: u8 = 2;

    /// Constructs a positive bounded history page size.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidNodeAttemptPageSize`] for zero or values
    /// above two.
    pub const fn new(value: u8) -> Result<Self, StoreError> {
        if value == 0 || value > Self::MAX {
            return Err(StoreError::InvalidNodeAttemptPageSize);
        }
        Ok(Self(value))
    }

    /// Returns the page size as an integer.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

/// One bounded, fully verified ascending physical-attempt history page.
#[derive(Clone, Debug)]
pub struct NodeAttemptHistoryPage {
    pub(crate) records: Vec<NodeAttempt>,
    pub(crate) has_more: bool,
}

impl NodeAttemptHistoryPage {
    /// Returns immutable physical attempts in ascending start order.
    #[must_use]
    pub fn records(&self) -> &[NodeAttempt] {
        &self.records
    }

    /// Returns whether a later physical attempt remains in the snapshot.
    #[must_use]
    pub const fn has_more(&self) -> bool {
        self.has_more
    }

    /// Returns the full last attempt required as the exact next-page cursor.
    #[must_use]
    pub fn next_cursor(&self) -> Option<NodeAttempt> {
        self.records.last().cloned()
    }
}

/// Hard-bounded number of fully decoded pending results in one recovery page.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PendingNodeResultPageSize(u8);

impl PendingNodeResultPageSize {
    /// Largest page accepted by the provider.
    ///
    /// One canonical pending result may occupy 16 MiB and can reference large
    /// model records that are verified in bounded sub-batches. Two retained
    /// results cap provider-owned decoded page memory near 32 MiB before driver
    /// and invocation-verification overhead. Look-ahead rows remain compact.
    pub const MAX: u8 = 2;

    /// Constructs a positive bounded pending-result page size.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidPendingNodeResultPageSize`] for zero or
    /// values above two.
    pub const fn new(value: u8) -> Result<Self, StoreError> {
        if value == 0 || value > Self::MAX {
            return Err(StoreError::InvalidPendingNodeResultPageSize);
        }
        Ok(Self(value))
    }

    /// Returns the page size as an integer.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

/// Exact stable-snapshot continuation for unconsumed pending-result scanning.
///
/// The cursor binds the immutable base checkpoint, the run journal head seen
/// by the first page, and the last fully verified result. A later result commit
/// changes the run journal head, making continuation fail explicitly instead
/// of silently skipping a newly inserted lower sort key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PendingNodeResultPageCursor {
    pub(crate) base_checkpoint: CheckpointHead,
    pub(crate) snapshot_journal_head: JournalHead,
    pub(crate) after: PendingNodeResultHead,
}

impl PendingNodeResultPageCursor {
    /// Returns the exact checkpoint whose unconsumed set is being scanned.
    #[must_use]
    pub const fn base_checkpoint(&self) -> &CheckpointHead {
        &self.base_checkpoint
    }

    /// Returns the run head that must remain unchanged across page calls.
    #[must_use]
    pub const fn snapshot_journal_head(&self) -> &JournalHead {
        &self.snapshot_journal_head
    }

    /// Returns the last fully verified result from the preceding page.
    #[must_use]
    pub const fn after(&self) -> &PendingNodeResultHead {
        &self.after
    }
}

/// One bounded, fully verified page of unconsumed pending node results.
#[derive(Clone, Debug)]
pub struct PendingNodeResultPage {
    pub(crate) base_checkpoint: CheckpointHead,
    pub(crate) snapshot_journal_head: JournalHead,
    pub(crate) records: Vec<PendingNodeResult>,
    pub(crate) has_more: bool,
}

impl PendingNodeResultPage {
    /// Returns the exact base checkpoint observed by this page.
    #[must_use]
    pub const fn base_checkpoint(&self) -> &CheckpointHead {
        &self.base_checkpoint
    }

    /// Returns the stable run journal head shared by every page continuation.
    #[must_use]
    pub const fn snapshot_journal_head(&self) -> &JournalHead {
        &self.snapshot_journal_head
    }

    /// Returns immutable pending results in canonical activation order.
    #[must_use]
    pub fn records(&self) -> &[PendingNodeResult] {
        &self.records
    }

    /// Consumes the page and returns its fully verified records without cloning
    /// their bounded JSON payloads.
    #[must_use]
    pub fn into_records(self) -> Vec<PendingNodeResult> {
        self.records
    }

    /// Returns whether a later result remains in the observed snapshot.
    #[must_use]
    pub const fn has_more(&self) -> bool {
        self.has_more
    }

    /// Returns the exact continuation required for the next page.
    #[must_use]
    pub fn next_cursor(&self) -> Option<PendingNodeResultPageCursor> {
        self.records
            .last()
            .map(|result| PendingNodeResultPageCursor {
                base_checkpoint: self.base_checkpoint.clone(),
                snapshot_journal_head: self.snapshot_journal_head.clone(),
                after: result.head(),
            })
    }
}

/// Hard-bounded number of model invocation revisions in one history page.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ModelInvocationHistoryPageSize(u8);

impl ModelInvocationHistoryPageSize {
    /// Largest page accepted by the provider.
    ///
    /// A compact revision and its separately loaded intent may each occupy up
    /// to 128 MiB, so the provider admits only one revision per decoded page.
    pub const MAX: u8 = 1;

    /// Constructs a positive bounded history page size.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidModelInvocationPageSize`] unless `value` is one.
    pub const fn new(value: u8) -> Result<Self, StoreError> {
        if value != Self::MAX {
            return Err(StoreError::InvalidModelInvocationPageSize);
        }
        Ok(Self(value))
    }

    /// Returns the page size as an integer.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

/// One bounded, fully verified ascending model-invocation history page.
#[derive(Clone, Debug)]
pub struct ModelInvocationHistoryPage {
    pub(crate) records: Vec<ModelInvocation>,
    pub(crate) has_more: bool,
}

impl ModelInvocationHistoryPage {
    /// Returns immutable revisions in ascending order.
    #[must_use]
    pub fn records(&self) -> &[ModelInvocation] {
        &self.records
    }

    /// Returns whether a later revision remains in the observed snapshot.
    #[must_use]
    pub const fn has_more(&self) -> bool {
        self.has_more
    }

    /// Returns the full last record required as the exact next-page cursor.
    #[must_use]
    pub fn next_cursor(&self) -> Option<ModelInvocation> {
        self.records.last().cloned()
    }
}

/// Hard-bounded number of invocation revisions returned in one history page.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ToolInvocationHistoryPageSize(u8);

impl ToolInvocationHistoryPageSize {
    /// Largest page accepted by the provider.
    ///
    /// One canonical record may occupy up to 16 MiB, so two records cap the
    /// provider-owned decoded page near 32 MiB before driver overhead.
    pub const MAX: u8 = 2;

    /// Constructs a positive bounded history page size.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidToolInvocationPageSize`] for zero or values
    /// above two.
    pub const fn new(value: u8) -> Result<Self, StoreError> {
        if value == 0 || value > Self::MAX {
            return Err(StoreError::InvalidToolInvocationPageSize);
        }
        Ok(Self(value))
    }

    /// Returns the page size as an integer.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

/// One bounded, fully verified ascending invocation-history page.
#[derive(Clone, Debug)]
pub struct ToolInvocationHistoryPage {
    pub(crate) records: Vec<ToolInvocation>,
    pub(crate) has_more: bool,
}

impl ToolInvocationHistoryPage {
    /// Returns immutable revisions in ascending order.
    #[must_use]
    pub fn records(&self) -> &[ToolInvocation] {
        &self.records
    }

    /// Returns whether a later revision remains in the observed snapshot.
    #[must_use]
    pub const fn has_more(&self) -> bool {
        self.has_more
    }

    /// Returns the full last record required as the exact next-page cursor.
    #[must_use]
    pub fn next_cursor(&self) -> Option<ToolInvocation> {
        self.records.last().cloned()
    }
}

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

/// Lifecycle projection to commit atomically with one journal append.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum RunProjection {
    /// Preserve the current lifecycle bytes and revision.
    Unchanged,
    /// Apply one pure lifecycle transition after matching the exact revision.
    Transition {
        /// Revision from which the pure lifecycle transition was derived.
        expected_revision: RunRevision,
        /// Transition to apply to the locked durable lifecycle.
        transition: RunTransition,
    },
}

/// Compact current-checkpoint pointer projected into the locked run row.
///
/// The full checkpoint must still be loaded and validated before recovery.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CheckpointPointer {
    pub(crate) checkpoint_id: CheckpointId,
    pub(crate) superstep: Superstep,
    pub(crate) digest: Digest,
}

impl CheckpointPointer {
    /// Returns the immutable checkpoint identity.
    #[must_use]
    pub const fn checkpoint_id(&self) -> CheckpointId {
        self.checkpoint_id
    }

    /// Returns the current committed barrier position.
    #[must_use]
    pub const fn superstep(&self) -> Superstep {
        self.superstep
    }

    /// Returns the complete checkpoint checksum.
    #[must_use]
    pub const fn digest(&self) -> Digest {
        self.digest
    }
}

/// Hard-bounded number of checkpoints returned in one lineage page.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct CheckpointLineagePageSize(u8);

impl CheckpointLineagePageSize {
    /// Largest page accepted by the provider.
    ///
    /// One checkpoint envelope may occupy roughly 2.5 MiB, so this deliberately
    /// remains much smaller than [`JournalPageSize::MAX`]. The provider may
    /// decode one additional parent as a fail-closed lineage look-ahead.
    pub const MAX: u8 = 8;

    /// Constructs a positive bounded checkpoint-lineage page size.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidCheckpointPageSize`] for zero or values
    /// above eight.
    pub const fn new(value: u8) -> Result<Self, StoreError> {
        if value == 0 || value > Self::MAX {
            return Err(StoreError::InvalidCheckpointPageSize);
        }
        Ok(Self(value))
    }

    /// Returns the page size as an integer.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

/// One bounded, fully verified reverse checkpoint-lineage page.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CheckpointLineagePage {
    pub(crate) checkpoints: Vec<Checkpoint>,
    pub(crate) next_cursor: Option<CheckpointHead>,
}

impl CheckpointLineagePage {
    /// Returns checkpoints in newest-to-oldest lineage order.
    #[must_use]
    pub fn checkpoints(&self) -> &[Checkpoint] {
        &self.checkpoints
    }

    /// Returns whether older ancestors remain before the superstep-zero root.
    #[must_use]
    pub const fn has_more(&self) -> bool {
        self.next_cursor.is_some()
    }

    /// Returns the exact parent head at which the next reverse page must start.
    #[must_use]
    pub fn next_cursor(&self) -> Option<CheckpointHead> {
        self.next_cursor.clone()
    }
}

/// Memory ceiling for independently replaying one historical graph barrier.
///
/// The provider measures the compact serialized size of every fully verified
/// pending result before retaining it for the deterministic planner. A single
/// bounded result may transiently sit beside the retained set while the limit
/// check runs, but the configured aggregate is never exceeded after insertion.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct GraphReplayLimits {
    maximum_barrier_result_bytes: usize,
}

impl GraphReplayLimits {
    /// Absolute implementation maximum for retained results in one barrier.
    pub const HARD_MAXIMUM_BARRIER_RESULT_BYTES: usize = 512 * 1024 * 1024;

    /// Constructs a positive replay memory ceiling.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidGraphReplayLimits`] for zero or more than
    /// 512 MiB.
    pub const fn new(maximum_barrier_result_bytes: usize) -> Result<Self, StoreError> {
        if maximum_barrier_result_bytes == 0
            || maximum_barrier_result_bytes > Self::HARD_MAXIMUM_BARRIER_RESULT_BYTES
        {
            return Err(StoreError::InvalidGraphReplayLimits);
        }
        Ok(Self {
            maximum_barrier_result_bytes,
        })
    }

    /// Returns the retained compact-result byte ceiling per barrier.
    #[must_use]
    pub const fn maximum_barrier_result_bytes(self) -> usize {
        self.maximum_barrier_result_bytes
    }
}

impl Default for GraphReplayLimits {
    fn default() -> Self {
        Self {
            maximum_barrier_result_bytes: 64 * 1024 * 1024,
        }
    }
}

/// Evidence summary returned after complete noninitial checkpoint replay.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GraphReplayReport {
    pub(crate) checkpoints_validated: u64,
    pub(crate) barriers_replayed: u64,
    pub(crate) results_replayed: u64,
    pub(crate) maximum_barrier_result_bytes: usize,
}

impl GraphReplayReport {
    /// Returns every checkpoint whose lineage and graph binding was verified.
    #[must_use]
    pub const fn checkpoints_validated(self) -> u64 {
        self.checkpoints_validated
    }

    /// Returns the number of parent-to-child transitions independently planned.
    #[must_use]
    pub const fn barriers_replayed(self) -> u64 {
        self.barriers_replayed
    }

    /// Returns the total number of immutable node results re-evaluated.
    #[must_use]
    pub const fn results_replayed(self) -> u64 {
        self.results_replayed
    }

    /// Returns the largest retained compact result set observed for one barrier.
    #[must_use]
    pub const fn maximum_barrier_result_bytes(self) -> usize {
        self.maximum_barrier_result_bytes
    }
}

impl RunProjection {
    /// Constructs a no-op lifecycle projection.
    #[must_use]
    pub const fn unchanged() -> Self {
        Self::Unchanged
    }

    /// Constructs an exact-revision pure lifecycle transition.
    #[must_use]
    pub const fn transition(expected_revision: RunRevision, transition: RunTransition) -> Self {
        Self::Transition {
            expected_revision,
            transition,
        }
    }
}

/// Hard-bounded size for tenant-level timer/interrupt discovery pages.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct WaitDiscoveryPageSize(u8);

impl WaitDiscoveryPageSize {
    /// Largest page accepted by the provider.
    pub const MAX: u8 = 16;

    /// Constructs a positive bounded discovery page size.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidWaitDiscoveryPageSize`] outside `1..=16`.
    pub const fn new(value: u8) -> Result<Self, StoreError> {
        if value == 0 || value > Self::MAX {
            return Err(StoreError::InvalidWaitDiscoveryPageSize);
        }
        Ok(Self(value))
    }

    /// Returns the page size as an integer.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

/// Opaque continuation for one fixed-cutoff due-timer scan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DueTimerPageCursor {
    pub(crate) tenant_id: stateknot_core::TenantId,
    pub(crate) snapshot_at: Timestamp,
    pub(crate) due_at: Timestamp,
    pub(crate) run_id: stateknot_core::RunId,
    pub(crate) timer_id: stateknot_core::TimerId,
}

/// One bounded tenant-level page of fully verified outstanding due timers.
#[derive(Clone, Debug)]
pub struct DueTimerPage {
    pub(crate) tenant_id: stateknot_core::TenantId,
    pub(crate) snapshot_at: Timestamp,
    pub(crate) records: Vec<DurableTimer>,
    pub(crate) has_more: bool,
}

impl DueTimerPage {
    /// Returns the database-time cutoff fixed for this page chain.
    #[must_use]
    pub const fn snapshot_at(&self) -> Timestamp {
        self.snapshot_at
    }

    /// Returns timers ordered by due time, run identity, then timer identity.
    #[must_use]
    pub fn records(&self) -> &[DurableTimer] {
        &self.records
    }

    /// Returns whether another matching row remained after this page.
    #[must_use]
    pub const fn has_more(&self) -> bool {
        self.has_more
    }

    /// Returns the exact key required to continue the fixed-cutoff scan.
    #[must_use]
    pub fn next_cursor(&self) -> Option<DueTimerPageCursor> {
        self.records.last().map(|timer| DueTimerPageCursor {
            tenant_id: self.tenant_id.clone(),
            snapshot_at: self.snapshot_at,
            due_at: timer.marker().due_at(),
            run_id: timer.intent().run_id(),
            timer_id: timer.marker().timer_id(),
        })
    }
}

/// Opaque continuation for one fixed-cutoff expired-interrupt scan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExpiredInterruptPageCursor {
    pub(crate) tenant_id: stateknot_core::TenantId,
    pub(crate) snapshot_at: Timestamp,
    pub(crate) expires_at: Timestamp,
    pub(crate) run_id: stateknot_core::RunId,
    pub(crate) interrupt_id: stateknot_core::InterruptId,
}

/// One bounded tenant-level page of fully verified outstanding expired interrupts.
#[derive(Clone, Debug)]
pub struct ExpiredInterruptPage {
    pub(crate) tenant_id: stateknot_core::TenantId,
    pub(crate) snapshot_at: Timestamp,
    pub(crate) records: Vec<InterruptRequest>,
    pub(crate) has_more: bool,
}

impl ExpiredInterruptPage {
    /// Returns the database-time cutoff fixed for this page chain.
    #[must_use]
    pub const fn snapshot_at(&self) -> Timestamp {
        self.snapshot_at
    }

    /// Returns requests ordered by expiry, run identity, then interrupt identity.
    #[must_use]
    pub fn records(&self) -> &[InterruptRequest] {
        &self.records
    }

    /// Returns whether another matching row remained after this page.
    #[must_use]
    pub const fn has_more(&self) -> bool {
        self.has_more
    }

    /// Returns the exact key required to continue the fixed-cutoff scan.
    #[must_use]
    pub fn next_cursor(&self) -> Option<ExpiredInterruptPageCursor> {
        let request = self.records.last()?;
        Some(ExpiredInterruptPageCursor {
            tenant_id: self.tenant_id.clone(),
            snapshot_at: self.snapshot_at,
            expires_at: request.marker().expires_at()?,
            run_id: request.intent().run_id(),
            interrupt_id: request.marker().interrupt_id(),
        })
    }
}

/// Validated durable snapshot of one tenant-scoped run row.
#[derive(Clone, Debug)]
pub struct StoredRun {
    pub(crate) lifecycle: RunLifecycle,
    pub(crate) journal_head: Option<JournalHead>,
    pub(crate) lease: Option<RunLease>,
    pub(crate) last_fencing_epoch: Option<FencingEpoch>,
    pub(crate) checkpoint: Option<CheckpointPointer>,
    pub(crate) scheduler_ready_at: Option<stateknot_core::Timestamp>,
    pub(crate) scheduler_not_before: Option<stateknot_core::Timestamp>,
    pub(crate) wait_set_digest: Option<Digest>,
    pub(crate) unresolved_wait_count: u8,
    pub(crate) next_timer_due_at: Option<Timestamp>,
    pub(crate) next_interrupt_expiry_at: Option<Timestamp>,
    pub(crate) quarantined: bool,
}

impl StoredRun {
    /// Returns current validated business lifecycle.
    #[must_use]
    pub const fn lifecycle(&self) -> &RunLifecycle {
        &self.lifecycle
    }

    /// Returns the current exact journal head, if non-empty.
    #[must_use]
    pub const fn journal_head(&self) -> Option<&JournalHead> {
        self.journal_head.as_ref()
    }

    /// Returns the active lease, including an expired lease not yet reclaimed.
    #[must_use]
    pub const fn lease(&self) -> Option<&RunLease> {
        self.lease.as_ref()
    }

    /// Returns the last issued fencing epoch; an unleased new run has none.
    #[must_use]
    pub const fn last_fencing_epoch(&self) -> Option<FencingEpoch> {
        self.last_fencing_epoch
    }

    /// Returns the compact current-checkpoint pointer, if the graph has reached
    /// its first durable barrier.
    #[must_use]
    pub const fn checkpoint(&self) -> Option<&CheckpointPointer> {
        self.checkpoint.as_ref()
    }

    /// Returns when the run most recently entered the durable scheduler queue.
    ///
    /// Waiting and terminal runs have no readiness observation. A live or
    /// expired lease can delay actual availability beyond this instant.
    #[must_use]
    pub const fn scheduler_ready_at(&self) -> Option<stateknot_core::Timestamp> {
        self.scheduler_ready_at
    }

    /// Returns the durable execution gate for a verified delayed node retry.
    ///
    /// Queue age remains available through [`Self::scheduler_ready_at`]. A
    /// scheduler must not claim this run before the inclusive instant returned
    /// here. Claiming at or after the boundary clears the gate atomically.
    #[must_use]
    pub const fn scheduler_not_before(&self) -> Option<stateknot_core::Timestamp> {
        self.scheduler_not_before
    }

    /// Returns the integrity checksum of the current ordered outstanding wait set.
    #[must_use]
    pub const fn wait_set_digest(&self) -> Option<Digest> {
        self.wait_set_digest
    }

    /// Returns the number of outstanding interrupt/timer registrations.
    #[must_use]
    pub const fn unresolved_wait_count(&self) -> u8 {
        self.unresolved_wait_count
    }

    /// Returns the earliest outstanding timer due instant, when present.
    #[must_use]
    pub const fn next_timer_due_at(&self) -> Option<Timestamp> {
        self.next_timer_due_at
    }

    /// Returns the earliest finite outstanding interrupt expiry, when present.
    #[must_use]
    pub const fn next_interrupt_expiry_at(&self) -> Option<Timestamp> {
        self.next_interrupt_expiry_at
    }

    /// Returns whether integrity or operator policy quarantined the run.
    #[must_use]
    pub const fn is_quarantined(&self) -> bool {
        self.quarantined
    }
}

/// Hard-bounded number of fully decoded runnable runs in one scheduler page.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RunnableRunPageSize(u8);

impl RunnableRunPageSize {
    /// Largest page accepted by the provider.
    ///
    /// One lifecycle envelope may occupy two MiB. Sixteen retained records plus
    /// one driver look-ahead row bound provider-owned page memory near 34 MiB.
    pub const MAX: u8 = 16;

    /// Constructs a positive bounded runnable-run page size.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidRunnableRunPageSize`] for zero or values
    /// above sixteen.
    pub const fn new(value: u8) -> Result<Self, StoreError> {
        if value == 0 || value > Self::MAX {
            return Err(StoreError::InvalidRunnableRunPageSize);
        }
        Ok(Self(value))
    }

    /// Returns the page size as an integer.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

/// One fully validated run visible to the tenant-level scheduler scan.
#[derive(Clone, Debug)]
pub struct RunnableRunCandidate {
    pub(crate) run: StoredRun,
    pub(crate) ready_at: stateknot_core::Timestamp,
    pub(crate) available_at: stateknot_core::Timestamp,
}

impl RunnableRunCandidate {
    /// Returns the complete validated durable run projection.
    #[must_use]
    pub const fn run(&self) -> &StoredRun {
        &self.run
    }

    /// Returns the database observation that inserted the run into the queue.
    #[must_use]
    pub const fn ready_at(&self) -> stateknot_core::Timestamp {
        self.ready_at
    }

    /// Returns the effective claim time after applying retry and lease gates.
    #[must_use]
    pub const fn available_at(&self) -> stateknot_core::Timestamp {
        self.available_at
    }
}

/// Opaque continuation for one fixed runnable-run database snapshot.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RunnableRunPageCursor {
    pub(crate) tenant_id: stateknot_core::TenantId,
    pub(crate) snapshot_at: stateknot_core::Timestamp,
    pub(crate) available_at: stateknot_core::Timestamp,
    pub(crate) run_id: stateknot_core::RunId,
}

/// One stable, bounded tenant-level scheduler candidate page.
#[derive(Clone, Debug)]
pub struct RunnableRunPage {
    pub(crate) tenant_id: stateknot_core::TenantId,
    pub(crate) snapshot_at: stateknot_core::Timestamp,
    pub(crate) records: Vec<RunnableRunCandidate>,
    pub(crate) has_more: bool,
}

impl RunnableRunPage {
    /// Returns the database time fixed for the complete page chain.
    #[must_use]
    pub const fn snapshot_at(&self) -> stateknot_core::Timestamp {
        self.snapshot_at
    }

    /// Returns candidates ordered by effective availability then run identity.
    #[must_use]
    pub fn records(&self) -> &[RunnableRunCandidate] {
        &self.records
    }

    /// Returns whether another candidate remained in this fixed snapshot.
    #[must_use]
    pub const fn has_more(&self) -> bool {
        self.has_more
    }

    /// Returns the opaque exact key required to continue this snapshot.
    #[must_use]
    pub fn next_cursor(&self) -> Option<RunnableRunPageCursor> {
        self.records.last().map(|candidate| RunnableRunPageCursor {
            tenant_id: self.tenant_id.clone(),
            snapshot_at: self.snapshot_at,
            available_at: candidate.available_at,
            run_id: candidate.run.lifecycle().provenance().run_id(),
        })
    }
}

/// Result of a lease renewal with stable desired expiry.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LeaseRenewalOutcome {
    /// Renewal extended the durable expiry.
    Renewed(RunLease),
    /// The same desired expiry had already committed.
    Idempotent(RunLease),
}

/// Exact lease proven live at one database-clock observation.
///
/// This is short-lived authority evidence, not a promise that the lease remains
/// live after [`Self::observed_at`]. Callers performing external work must
/// translate the remaining database duration into a conservative monotonic
/// deadline and continue renewing beneath the same fence.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LiveLeaseObservation {
    pub(crate) lease: RunLease,
    pub(crate) observed_at: Timestamp,
}

impl LiveLeaseObservation {
    /// Returns the exact fence and exclusive durable expiry observed.
    #[must_use]
    pub const fn lease(&self) -> &RunLease {
        &self.lease
    }

    /// Returns the database clock used to prove the lease unexpired.
    #[must_use]
    pub const fn observed_at(&self) -> Timestamp {
        self.observed_at
    }

    /// Consumes the observation into its lease and database time.
    #[must_use]
    pub fn into_parts(self) -> (RunLease, Timestamp) {
        (self.lease, self.observed_at)
    }
}

/// Result of claiming or explicitly superseding execution ownership.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LeaseClaimOutcome {
    /// A new attempt and successor fencing epoch committed.
    Claimed(RunLease),
    /// The same stable attempt already owns the current unexpired lease.
    Idempotent(RunLease),
}

impl LeaseClaimOutcome {
    /// Returns the current validated lease.
    #[must_use]
    pub const fn lease(&self) -> &RunLease {
        match self {
            Self::Claimed(lease) | Self::Idempotent(lease) => lease,
        }
    }
}

impl LeaseRenewalOutcome {
    /// Returns the current validated lease.
    #[must_use]
    pub const fn lease(&self) -> &RunLease {
        match self {
            Self::Renewed(lease) | Self::Idempotent(lease) => lease,
        }
    }
}

/// Result of an exact-fence lease release.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LeaseReleaseOutcome {
    /// The active lease was cleared.
    Released,
    /// The exact epoch was already released and no successor was issued.
    Idempotent,
}

/// Result of projecting a recovery plan's delayed retry into scheduler state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DelayedRetryScheduleOutcome {
    /// The exact live lease was released and the durable wakeup was committed.
    Scheduled {
        /// Inclusive earliest database instant for another scheduler claim.
        not_before: Timestamp,
    },
    /// The same fence and wakeup had already committed before acknowledgement.
    Idempotent {
        /// Inclusive earliest database instant already stored for the run.
        not_before: Timestamp,
    },
    /// Database time reached the retry boundary before the deferral committed.
    ///
    /// The caller retains its lease and should rebuild the recovery plan rather
    /// than release and immediately reclaim the same run.
    Due {
        /// Inclusive retry boundary from the supplied verified plan.
        not_before: Timestamp,
    },
}

impl DelayedRetryScheduleOutcome {
    /// Returns the inclusive retry boundary shared by every outcome.
    #[must_use]
    pub const fn not_before(self) -> Timestamp {
        match self {
            Self::Scheduled { not_before }
            | Self::Idempotent { not_before }
            | Self::Due { not_before } => not_before,
        }
    }
}

/// Hard-bounded number of events returned by one journal read.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct JournalPageSize(u16);

impl JournalPageSize {
    /// Largest page accepted by the provider.
    pub const MAX: u16 = 1_000;

    /// Constructs a positive bounded page size.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::InvalidPageSize`] for zero or values above 1,000.
    pub const fn new(value: u16) -> Result<Self, StoreError> {
        if value == 0 || value > Self::MAX {
            return Err(StoreError::InvalidPageSize);
        }
        Ok(Self(value))
    }

    /// Returns the page size as an integer.
    #[must_use]
    pub const fn get(self) -> u16 {
        self.0
    }
}

/// One bounded, validated page from a run journal.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct JournalPage {
    pub(crate) events: Vec<JournalEvent>,
    pub(crate) has_more: bool,
}

impl JournalPage {
    /// Returns events in ascending contiguous sequence order.
    #[must_use]
    pub fn events(&self) -> &[JournalEvent] {
        &self.events
    }

    /// Returns whether another page exists after the final returned sequence.
    #[must_use]
    pub const fn has_more(&self) -> bool {
        self.has_more
    }

    /// Returns the complete final event head to use as the next exact cursor.
    #[must_use]
    pub fn next_cursor(&self) -> Option<JournalHead> {
        self.events.last().map(JournalEvent::head)
    }
}