meerkat-machine-schema 0.7.16

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

use meerkat_machine_dsl::machine;

use super::OptionValueExt;

/// Bridging key type for session identity. Maps to `meerkat_core::SessionId`.
///
/// The DSL needs `Ord + Hash + Clone` for `Map` keys; this newtype satisfies
/// that while staying a thin wrapper over the session id string.
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Default,
    serde::Serialize,
    serde::Deserialize,
)]
pub struct SessionId(pub String);

impl<T: Into<String>> From<T> for SessionId {
    fn from(value: T) -> Self {
        Self(value.into())
    }
}

impl SessionId {
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Per-session first-turn lifecycle phase.
///
/// `Inactive` is the default (and the value for any session id absent from the
/// `session_first_turn_phase` map), `Pending` means the deferred first turn is
/// staged but not yet started, and `Consumed` is the absorbing terminal phase
/// once the first turn has started.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum SessionFirstTurnPhase {
    #[default]
    Inactive,
    Pending,
    Consumed,
}

/// Disposition for an initial-prompt staging decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum SessionInitialPromptStageDecision {
    #[default]
    Clear,
    Store,
}

/// Disposition for a runtime system-context append-staging decision.
///
/// Ported verbatim from the retired `SessionSystemContextAuthorityMachine`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum SystemContextAppendDecision {
    #[default]
    Staged,
    Duplicate,
    RejectEmpty,
    RejectConflict,
}

/// Machine-owned admission verdict for a PERSIST-TIME system-context append
/// continuity check.
///
/// The session store's atomic append-only save guard must decide whether an
/// incoming persisted system prompt is an admissible runtime-context-append
/// continuation of the previously persisted one. This is the SAME machine that
/// owns the staging-path append disposition ([`SystemContextAppendDecision`]);
/// the persist-time decision is its own append-admission verdict over the
/// structural prefix observations plus the typed `is_runtime_context_append`
/// provenance marker (NOT a `[Runtime System Context]` content prefix). The
/// session-store shell extracts those pure observations, drives
/// `ResolveSystemContextPersistAppendAdmission`, and mirrors the verdict:
/// `Admit` -> the divergence is an admissible append, `Reject` -> it is not.
/// Fails closed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum SystemContextPersistAppendAdmission {
    #[default]
    Reject,
    Admit,
}

/// Typed provenance class for a runtime system-context append.
///
/// This is the canonical replacement for the retired `runtime:steer:` string
/// prefix folklore: the producer of a runtime-steer append constructs it with
/// [`SystemContextSource::RuntimeSteer`]; everything else is
/// [`SystemContextSource::Normal`]. The machine guards the typed field — no
/// generated or shell code reclassifies a source string into this fact.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum SystemContextSource {
    #[default]
    Normal,
    RuntimeSteer,
}

// ---------------------------------------------------------------------------
// Realtime-transcript region typed vocabulary (folded from the retired
// SessionRealtimeTranscriptAuthorityMachine).
//
// These are the SAME typed observation/decision enums the retired machine
// carried. The bulky per-item registry (`SessionRealtimeTranscriptState`,
// the content-segment maps, the causal ordering, message assembly) stays a
// NON-generated shell helper in meerkat-core: the DSL has no string-content
// op, no topological-order op, and no materialize-loop construct, so the
// shell computes those mechanical facts and feeds them as typed RAW
// observations. The machine decides the action vector / materialize verdict
// from those observations — never the other way around.
// ---------------------------------------------------------------------------

/// Provider-neutral role for a realtime transcript item.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum RealtimeTranscriptRoleKind {
    #[default]
    User,
    Assistant,
}

/// Output lane carried by an assistant realtime transcript item.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum RealtimeTranscriptLaneKind {
    #[default]
    Display,
    Spoken,
}

/// Terminal-boundary stop-reason class observed for a realtime assistant turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum RealtimeTranscriptStopReasonKind {
    Cancelled,
    ToolUse,
    #[default]
    Other,
}

/// Per-item materialization verdict.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum RealtimeTranscriptMaterializeDecision {
    #[default]
    Wait,
    MarkSkipped,
    MaterializeUser,
    MaterializeAssistant,
}

// ---------------------------------------------------------------------------
// Durable-config region typed vocabulary (folded from the retired
// SessionDurableConfigAuthorityMachine).
//
// The metadata-persist / build-state-persist / build-state-restore admission
// verdicts branch only on a handful of decision-relevant facts (schema
// version, model presence, mob-tool authority context kind), so those are the
// only typed observations the inputs carry. The bulky `SessionMetadata` /
// `SessionBuildState` records stay in the meerkat-core shell; a config field
// the verdict never reads is not an authority input and is not modeled here.
// ---------------------------------------------------------------------------

/// Typed provenance class for a system-prompt mutation request.
///
/// This is carried on the mutation request so every provenance is a typed
/// fact at the seam (no `source` string folklore). The mutation guard does not
/// branch on the provenance — the verdict is decided from prompt presence —
/// but keeping the class typed pins the producer's intent at the boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum SessionSystemPromptSource {
    #[default]
    DirectMutation,
    ExplicitBuild,
    DefaultBuild,
    WasmDefaultBuild,
    RuntimeContextAppend,
    RuntimeSteerCleanup,
}

// ---------------------------------------------------------------------------
// Pending-continuation region typed vocabulary (folded from the retired
// non-canonical PendingContinuationAdmissionMachine).
//
// The pending-boundary is a session-document-tail-derived fact: given the
// typed `session_tail` class (the pure mechanical encoding of `messages.last()`
// produced by the `observe_session_tail` encoder, which stays a pure encoder)
// and the count of staged tool results, the machine decides whether a
// continuation has an effective pending boundary to run. This is the SAME
// `has_effective_pending_boundary` decision the retired machine carried; it now
// lives as a SessionDocumentMachine transition so both meerkat-core
// (`run_pending`) and meerkat-session (turn admission) drive the canonical
// machine and MIRROR the emitted disposition.
// ---------------------------------------------------------------------------

/// Provider-neutral class of the last message in a session's transcript.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum ObservedSessionTailKind {
    #[default]
    Empty,
    System,
    SystemNotice,
    User,
    BlockAssistant,
    ToolResults,
}

/// Disposition for a pending-continuation admission decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum PendingContinuationDisposition {
    RunPending,
    #[default]
    NoPendingBoundary,
}

/// Public terminal witness emitted alongside a `NoPendingBoundary` disposition.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum PendingContinuationPublicTerminal {
    #[default]
    NoPendingBoundary,
}

// ---------------------------------------------------------------------------
// Resume-override-admission region (folded from the handwritten
// session_recovery.rs `resolve_effective_turn_config` override-admission and
// `resolve_resume_llm_binding` shell helpers under LUC-524 Dogma Invariant 1).
//
// The shell computes only typed presence/override observations against the
// surface recovery overrides and the durable session defaults (including the
// RAW first-turn phase — NOT the already-reduced overrides-allowed verdict). It
// carries NO pre-decided admission verdict. The machine decides the
// accept/reject verdict AND the effective LLM-binding selection below; the
// first-turn-overrides legality is re-derived here from the raw phase via the
// same `phase_allows_initial_turn_overrides` helper the first-turn region uses.
// ---------------------------------------------------------------------------

/// Typed reason a resume-override admission was rejected. The shell maps each
/// variant to its existing typed recovery-error message; the verdict is the
/// machine's decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum ResumeOverrideRejection {
    #[default]
    ProviderRequiresModel,
    BuildOnlyAfterFirstTurn,
}

/// Effective provider selection for a resumed turn's LLM binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum ResumeProviderSelection {
    /// Recompute the provider from the (new) model — clear the stored provider.
    #[default]
    RecomputeFromModel,
    /// Use the explicit provider override.
    UseOverride,
    /// Retain the stored provider.
    UseStored,
}

/// Effective self-hosted-binding selection for a resumed turn's LLM binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum ResumeSelfHostedSelection {
    /// Clear the persisted self-hosted server binding (model changed).
    #[default]
    Clear,
    /// Retain the persisted self-hosted server binding.
    Retain,
}

/// Machine-decided live-vs-durable session-document authority verdict. The
/// session-store shell extracts four pure boolean observations of session-
/// document divergence and mirrors this verdict: `LiveAuthoritative` keeps the
/// live (runtime) session document; `DurableAuthoritative` supersedes it with
/// the stored durable document.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum LiveSessionAuthorityKind {
    /// The live (runtime) session document remains authoritative.
    #[default]
    LiveAuthoritative,
    /// The durable (stored) session document supersedes the live one.
    DurableAuthoritative,
}

/// Typed reason the durable session document superseded the live one. The
/// machine — not the shell — encodes the precedence (archived > uncommitted
/// transcript > runtime system-context divergence > stored transcript-revision
/// divergence) and mints this typed reason, replacing the prior `&'static str`
/// folklore. The shell mirrors the reason and branches on
/// `RuntimeSystemContextDiverged` for its runtime-context-only sync path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum LiveSessionAuthorityReason {
    /// The stored session document is archived.
    #[default]
    StoredArchived,
    /// The live transcript carries uncommitted (ahead-of-durable) messages.
    LiveUncommittedTranscript,
    /// The runtime system-context state diverged from durable truth.
    RuntimeSystemContextDiverged,
    /// The stored transcript revision diverged from the live revision.
    StoredTranscriptRevisionDiverged,
}

/// Disposition for a runtime-authoritative projection save whose durable
/// session-store row ran AHEAD of the runtime authority. The intra-turn
/// best-effort checkpointer writes the durable row while the machine boundary
/// commit writes the runtime-store snapshot; the two commit points are
/// non-atomic, so a host kill (or an in-process lifecycle-commit failure that
/// evicted the uncommitted live turn) leaves the row carrying turn content
/// the machine never committed. The runtime authority is singular: the row is
/// an explicitly rebuildable projection and must converge back to committed
/// truth rather than poisoning every subsequent save. The machine — not a
/// shell comparison — owns the disposition; the shell extracts the pure
/// continuation observation and mirrors the verdict.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum RuntimeProjectionRollbackDisposition {
    /// The row does not faithfully continue the authority transcript — a
    /// genuine content fork. The save fails closed exactly as before.
    #[default]
    RejectDivergent,
    /// The row is a faithful continuation of the authority transcript (its
    /// tail is turn content whose boundary commit never landed). The
    /// projection write is authorized to rebuild the row onto the authority
    /// transcript, discarding the unacknowledged tail.
    RebuildToAuthority,
}

// ---------------------------------------------------------------------------
// Lifecycle-terminal region (LUC-524 R004 fold). Archive lifecycle truth was
// MODE-SPLIT: runtime-backed archived-ness was owned by MeerkatMachine
// `Retire` while store-only archived-ness was owned by the session document's
// `session_lifecycle_terminal` metadata key, with a warn-continue divergence
// window (machine retired -> projection save failed -> durable doc stayed
// Active -> standalone reopen resurrected the session). THIS machine now owns
// the `lifecycle_terminal` fact for ALL profiles: both the runtime-backed and
// the store-only archive paths drive `ArchiveSessionDocument`, and the shell
// realizes the machine's action vector fail-closed (durable document commit
// FIRST, runtime retire SECOND — a failure anywhere fails the archive
// operation, so `RuntimeState::Retired` implies the durable document is
// Archived and the divergence window is unrepresentable).
// ---------------------------------------------------------------------------

/// Canonical lifecycle-terminal class for a session document. `Active` is the
/// default (and the recovered value for a document with no terminal fact);
/// `Archived` is the absorbing terminal class. Maps to
/// `meerkat_core::SessionLifecycleTerminal`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum SessionDocumentLifecycle {
    #[default]
    Active,
    Archived,
}

/// Machine-decided disposition for a session-document archive request.
///
/// Idempotence decision (documented contract): archiving an already-Archived
/// document resolves to the explicit `AlreadyArchived` verdict — a total
/// verdict, never a guard no-match — with an empty action vector (no document
/// re-write, no runtime retire). The public surface contract maps
/// `AlreadyArchived` to its existing `NotFound` error, so re-archive remains
/// observably idempotent at the API while the machine owns the decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum SessionArchiveDisposition {
    #[default]
    Archive,
    AlreadyArchived,
}

// ---------------------------------------------------------------------------
// Transcript-edit region (folded from the meerkat-session persistent.rs
// `persist_transcript_fork` / `persist_transcript_rewrite` commit paths under
// LUC-524). The persist paths commit a fork or rewrite DIRECTLY via
// `save_normalized_session` / `commit_session_transcript_rewrite_snapshot`
// with no machine authorization gate. This region authorizes the commit: the
// shell carries the typed `TranscriptEditKind` directive (fork vs rewrite) and
// drives the transition BEFORE persisting; `save_normalized_session` /
// `commit_session_transcript_rewrite_snapshot` become the effect HANDLER, not
// the decision-maker.
// ---------------------------------------------------------------------------

/// Typed class of an authorized transcript-edit commit.
///
/// `Fork` covers `fork_session` / `fork_session_replace` (the
/// `persist_transcript_fork` path); `Rewrite` covers
/// `rewrite_session_transcript` / `restore_session_transcript_revision` (the
/// `persist_transcript_rewrite` path). The producer constructs the typed
/// directive at the seam — no shell code reclassifies an edit kind from a
/// string.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum TranscriptEditKind {
    #[default]
    Fork,
    Rewrite,
}

machine! {
    machine SessionDocumentMachine {
        version: 1,
        rust: "self" / "catalog::dsl::session_document",

        state {
            lifecycle_phase: SessionDocumentPhase,
            session_first_turn_phase: Map<SessionId, Enum<SessionFirstTurnPhase>>,
            session_pending_initial_prompt_present: Map<SessionId, bool>,
            session_pending_tool_results_count: Map<SessionId, u64>,
            session_lifecycle_terminal: Map<SessionId, Enum<SessionDocumentLifecycle>>,
        }

        init(Ready) {
            session_first_turn_phase = EmptyMap,
            session_pending_initial_prompt_present = EmptyMap,
            session_pending_tool_results_count = EmptyMap,
            session_lifecycle_terminal = EmptyMap,
        }

        terminal []

        phase SessionDocumentPhase {
            Ready,
        }

        input SessionDocumentInput {
            MarkSessionInitialTurnPending { session_id: SessionId },
            StartSessionInitialTurn { session_id: SessionId },
            StageSessionInitialPrompt { session_id: SessionId, prompt_has_content: bool },
            StageSessionToolResults { session_id: SessionId, result_count: u64 },
            ConsumeSessionDeferredInputs { session_id: SessionId },
            RestoreSessionConsumedInputs {
                session_id: SessionId,
                restore_first_turn_pending: bool,
                pending_initial_prompt_present: bool,
                pending_tool_result_message_count: u64,
            },
            RecoverSessionFirstTurnPhase {
                session_id: SessionId,
                phase: Enum<SessionFirstTurnPhase>,
                pending_initial_prompt_present: bool,
                pending_tool_result_message_count: u64,
            },
            ResolveSessionFirstTurnOverridesAllowed { session_id: SessionId },

            // -----------------------------------------------------------
            // System-context region (folded from the retired
            // SessionSystemContextAuthorityMachine).
            //
            // The bulky append payloads (text/source strings, pending/applied
            // vectors, the seen map) stay in the shell's
            // `SessionSystemContextState`. The machine owns the per-append
            // SEMANTIC decisions: append disposition (RejectEmpty / Conflict /
            // Duplicate / Staged) and the runtime-steer apply/discard
            // disposition, which guards the TYPED `SystemContextSource` field
            // instead of a `runtime:steer:` string prefix.
            // -----------------------------------------------------------
            ResolveSystemContextAppend {
                trimmed_text_byte_count: u64,
                idempotency_key_present: bool,
                existing_key_matches: bool,
                existing_key_conflicts: bool,
                active_turn_scoped: bool,
            },
            // Per-pending-append decision for `mark_pending_applied`: a
            // runtime-steer append is dropped (and its seen entry removed); a
            // normal append is promoted to applied and its seen entry marked
            // applied. The machine guards the typed `source_kind`.
            ResolveSystemContextPendingApplyItem {
                source_kind: Enum<SystemContextSource>,
            },
            // Per-item decision for transient runtime-steer cleanup: discard
            // iff the typed `source_kind` is `RuntimeSteer`.
            ResolveSystemContextSteerCleanupItem {
                source_kind: Enum<SystemContextSource>,
            },
            // Snapshot-restore consistency authorization, ported verbatim.
            RestoreSystemContextSnapshot {
                active_keys_have_known_pending_or_seen: bool,
                seen_keys_match_known_appends: bool,
            },
            // Persist-time system-context append-admission continuity check.
            // The session-store atomic append-only save guard extracts the pure
            // structural observations (whether a previous system prompt exists,
            // whether the incoming content is byte-identical, whether it extends
            // the previous content as a prefix, whether the appended remainder
            // begins with the canonical separator) plus the typed
            // `is_runtime_context_append` provenance marker, and feeds them
            // here. THIS machine — not a handwritten shell bool reducer — owns
            // the verdict "is this incoming persisted prompt an admissible
            // runtime-context-append continuation of the persisted one". The
            // shell mirrors `Admit`/`Reject` and decides nothing.
            ResolveSystemContextPersistAppendAdmission {
                has_previous: bool,
                content_identical: bool,
                content_extends_previous: bool,
                appended_starts_with_separator: bool,
                incoming_is_runtime_context_append: bool,
            },

            // -----------------------------------------------------------
            // Realtime-transcript region (folded from the retired
            // SessionRealtimeTranscriptAuthorityMachine).
            //
            // Each input carries only typed RAW observations the shell
            // computes mechanically against its bulky
            // `SessionRealtimeTranscriptState` (set membership, segment
            // concat emptiness, per-item flags). NONE carries a pre-decided
            // action. The machine resolves the action vector / materialize
            // verdict below.
            // -----------------------------------------------------------
            ResolveRealtimeItemObserved {
                role: Enum<RealtimeTranscriptRoleKind>,
                response_discarded: bool,
            },
            ResolveRealtimeItemSkipped,
            ResolveRealtimeUserTranscriptFinal {
                text_present: bool,
                segment_empty: bool,
                segment_matches: bool,
            },
            ResolveRealtimeAssistantDelta {
                response_id_valid: bool,
                response_discarded: bool,
                delta_id_present: bool,
                delta_id_seen: bool,
                item_has_text: bool,
                current_lane: Enum<RealtimeTranscriptLaneKind>,
                requested_lane: Enum<RealtimeTranscriptLaneKind>,
                response_completed: bool,
                text_after_write_present: bool,
            },
            ResolveRealtimeAssistantTextReplacement {
                response_id_valid: bool,
                response_discarded: bool,
                item_materialized: bool,
                item_has_text: bool,
                current_lane: Enum<RealtimeTranscriptLaneKind>,
                requested_lane: Enum<RealtimeTranscriptLaneKind>,
                response_completed: bool,
                text_after_replace_present: bool,
            },
            ResolveRealtimeAssistantTurnCompleted {
                response_id_valid: bool,
                response_discarded: bool,
                stop_reason: Enum<RealtimeTranscriptStopReasonKind>,
            },
            ResolveRealtimeAssistantTurnInterrupted {
                response_id_valid: bool,
            },
            ResolveRealtimeMaterializeCandidate {
                item_materialized: bool,
                predecessor_materialized: bool,
                item_skipped: bool,
                item_ready: bool,
                item_text_present: bool,
                role: Enum<RealtimeTranscriptRoleKind>,
                response_id_present: bool,
                completion_present: bool,
                completion_usage_consumed: bool,
            },
            RestoreRealtimeTranscriptState {
                item_count: u64,
                first_seen_count: u64,
                first_seen_unique_count: u64,
                every_item_has_order_entry: bool,
                every_order_entry_has_item: bool,
                all_identity_fields_valid: bool,
                all_delta_ids_valid: bool,
                all_completion_response_ids_valid: bool,
                all_discarded_response_ids_valid: bool,
                all_materialized_items_were_ready_or_skipped: bool,
                all_assistant_items_have_response_unless_skipped: bool,
                all_ready_assistant_items_have_completion_or_are_skipped: bool,
                all_materialized_assistant_completions_consumed: bool,
                all_completed_assistant_text_items_are_ready_or_materialized_or_skipped: bool,
                all_discarded_assistant_items_are_skipped_or_materialized: bool,
            },

            // -----------------------------------------------------------
            // Durable-config region (folded from the retired
            // SessionDurableConfigAuthorityMachine).
            //
            // Each input carries ONLY the typed facts the machine's
            // authorization decision actually reads — it is NOT a mirror of
            // the shell's bulky `SessionMetadata` / `SessionBuildState` record.
            // The shell persists the full record; this machine owns the
            // admit/reject verdict over the decision-relevant facts alone
            // (modeling the full record as quantified inputs would be dead
            // weight here — the machine records none of it via `update {}` —
            // and an intractable TLC cross-product). NONE carries a
            // pre-decided verdict. Rejection surfaces as the input matching no
            // transition.
            // -----------------------------------------------------------
            AuthorizeSessionMetadataPersist {
                schema_version: u64,
                model_present: bool,
            },
            AuthorizeSessionBuildStatePersist {
                mob_tool_authority_context_present: bool,
                mob_tool_authority_context_generated: bool,
            },
            RestoreSessionBuildState,
            AuthorizeSystemPromptMutation {
                source: Enum<SessionSystemPromptSource>,
                prompt_present: bool,
                prompt_byte_count: u64,
                replacing_existing: bool,
            },

            // -----------------------------------------------------------
            // Pending-continuation region (folded from the retired
            // PendingContinuationAdmissionMachine). The input carries only the
            // typed RAW observations the shell computes mechanically (the
            // session-tail class from the pure `observe_session_tail` encoder
            // and the staged tool-result count). It carries NO pre-decided
            // disposition. The machine resolves RunPending / NoPendingBoundary
            // below from those observations via `has_effective_pending_boundary`.
            // -----------------------------------------------------------
            ResolvePendingContinuation {
                session_tail: Enum<ObservedSessionTailKind>,
                staged_tool_result_count: u64,
            },

            // -----------------------------------------------------------
            // Resume-override-admission region. The input carries only typed
            // presence/override observations and the RAW first-turn phase the
            // shell read from durable session state. It carries NO pre-decided
            // verdict. The machine resolves accept (with the effective
            // LLM-binding selection) or a typed rejection below.
            // -----------------------------------------------------------
            AuthorizeSessionResumeOverrides {
                provider_override_present: bool,
                model_override_present: bool,
                has_build_only_overrides: bool,
                first_turn_phase: Enum<SessionFirstTurnPhase>,
            },

            // -----------------------------------------------------------
            // Live-vs-durable session-document authority reconciliation. The
            // session-store shell extracts FOUR pure boolean observations of
            // session-document divergence (stored transcript revision diverged,
            // live transcript carries uncommitted messages, runtime
            // system-context diverged, stored document archived). It carries NO
            // pre-decided verdict and NO string reason. THIS machine — not a
            // handwritten boolean reducer — owns the LiveAuthoritative-vs-
            // DurableAuthoritative verdict AND the precedence (archived >
            // uncommitted transcript > runtime system-context > revision) AND
            // the typed reason. The shell mirrors the verdict + typed reason and
            // decides nothing.
            // -----------------------------------------------------------
            ClassifyLiveSessionAuthority {
                stored_transcript_diverged: bool,
                live_has_uncommitted_transcript: bool,
                runtime_system_context_diverged: bool,
                stored_is_archived: bool,
            },

            // -----------------------------------------------------------
            // Recovery-source-projection region (KEYSTONE, folded from the
            // meerkat-session persistent.rs shell predicate
            // `runtime_backed_store_projection_can_recover_authority`). When
            // the runtime snapshot is absent, the session-store projection may
            // stand in as the authoritative read source iff it carries
            // canonical session metadata, build state, or a generated runtime
            // projection quarantine fact. The shell extracts the typed
            // observations and drives this input; THIS
            // machine — not a handwritten shell `||` reducer — owns the
            // recoverable verdict. The shell mirrors `recoverable` onto its load
            // fallback (recoverable -> the projection is authoritative; not
            // recoverable -> `None`). Fails closed.
            // -----------------------------------------------------------
            RecoverSessionFromStore {
                session_id: SessionId,
                has_metadata: bool,
                has_build_state: bool,
                runtime_projection_quarantined: bool,
            },

            // -----------------------------------------------------------
            // Runtime-projection-rollback region. When a runtime-authoritative
            // projection save finds the durable session-store row AHEAD of the
            // authority transcript (intra-turn checkpointer row vs a machine
            // boundary commit that never landed — host kill or in-process
            // lifecycle-commit eviction), the shell extracts two pure
            // observations — the row judged as a faithful continuation of the
            // authority by the same run-boundary proof the save guard uses,
            // and the row's typed intra-turn checkpoint provenance fact — and
            // drives this input; THIS machine — not a handwritten shell
            // comparison — owns whether the projection write may rebuild the
            // row onto committed truth. A row without the checkpointer's own
            // provenance stamp is out-of-band divergence and keeps failing
            // closed. The shell mirrors the disposition and decides nothing.
            // -----------------------------------------------------------
            ResolveRuntimeProjectionRollback {
                session_id: SessionId,
                row_continues_authority: bool,
                row_is_runtime_checkpoint: bool,
            },

            // -----------------------------------------------------------
            // Apply-pending-tool-results region (folded from the
            // meerkat-session ephemeral.rs `agent.apply_pending_tool_results`
            // call site). Staging already consults generated authority for the
            // accepted COUNT (StageSessionToolResults); the APPLY of those
            // staged results into the live transcript was still a direct
            // mutation outside the turn machine. This input authorizes the
            // apply: the shell carries the consumed result count and drives the
            // transition; `agent.apply_pending_tool_results` becomes the effect
            // HANDLER driven by the emitted `applied_count`, not the decision
            // point.
            // -----------------------------------------------------------
            ApplyPendingToolResults {
                session_id: SessionId,
                result_count: u64,
            },

            // -----------------------------------------------------------
            // Transcript-edit region. The shell carries the typed
            // `TranscriptEditKind` directive (fork vs rewrite) and drives this
            // input BEFORE persisting; THIS machine authorizes the commit and
            // emits `TranscriptRewriteCommitted`. The persist paths
            // (`save_normalized_session` for fork,
            // `commit_session_transcript_rewrite_snapshot` for rewrite) become
            // the effect HANDLER driven by the verdict, not the decision-maker.
            // -----------------------------------------------------------
            TranscriptEdit {
                session_id: SessionId,
                fork_or_rewrite_directive: Enum<TranscriptEditKind>,
            },

            // -----------------------------------------------------------
            // Lifecycle-terminal region (LUC-524 R004 fold). The recover
            // input adopts the canonical current archived-ness observation
            // (runtime mode: the Retire realization; store-only mode: the
            // durable document's typed lifecycle-terminal fact) into the
            // machine-owned registry; the archive input then decides the
            // disposition and the realization action vector from the
            // machine-owned terminal state plus three pure mode
            // observations. Neither carries a pre-decided verdict.
            // -----------------------------------------------------------
            RecoverSessionLifecycleTerminal {
                session_id: SessionId,
                terminal: Enum<SessionDocumentLifecycle>,
            },
            ArchiveSessionDocument {
                session_id: SessionId,
                runtime_backed: bool,
                durable_snapshot_present: bool,
                runtime_session_registered: bool,
            },
        }

        effect SessionDocumentEffect {
            SessionFirstTurnPhaseResolved {
                phase: Enum<SessionFirstTurnPhase>,
                was_pending: bool,
            },
            SessionFirstTurnOverridesResolved { allowed: bool },
            SessionInitialPromptStageResolved { decision: Enum<SessionInitialPromptStageDecision> },
            SessionToolResultsStageResolved { accepted_count: u64 },
            SessionConsumedInputsRestoreResolved {
                restore_first_turn_pending: bool,
                restore_initial_prompt: bool,
                restore_tool_results: bool,
            },
            SessionFirstTurnPhaseRecovered,

            // System-context region effects.
            SystemContextAppendResolved {
                decision: Enum<SystemContextAppendDecision>,
                active_turn_scoped: bool,
            },
            // `promote_to_applied`/`mark_seen_applied` are emitted for normal
            // appends; `remove_seen` for runtime-steer appends. The shell
            // mirrors these onto its bulky pending/applied/seen collections.
            SystemContextPendingApplyItemResolved {
                promote_to_applied: bool,
                mark_seen_applied: bool,
                remove_seen: bool,
            },
            // `discard` is emitted true for runtime-steer items.
            SystemContextSteerCleanupItemResolved {
                discard: bool,
            },
            SystemContextSnapshotRestoreAuthorized,
            // Persist-time append-admission verdict. The session-store shell
            // mirrors `Admit`/`Reject` onto its atomic append-only save guard.
            SystemContextPersistAppendAdmissionResolved {
                admission: Enum<SystemContextPersistAppendAdmission>,
            },

            // Realtime-transcript region effects. The action vector is the
            // machine's decision; the shell mirrors each flag onto its bulky
            // `SessionRealtimeTranscriptState` and decides nothing.
            RealtimeTranscriptEventResolved {
                observe_item: bool,
                observe_skipped: bool,
                write_user_segment: bool,
                append_assistant_segment: bool,
                replace_assistant_segment: bool,
                promote_lane: bool,
                mark_item_ready: bool,
                record_delta_id: bool,
                remove_completion: bool,
                record_completion: bool,
                discard_response: bool,
                discard_response_by_lane: bool,
                mark_response_ready: bool,
                materialize_ready_items: bool,
            },
            RealtimeMaterializeCandidateResolved {
                decision: Enum<RealtimeTranscriptMaterializeDecision>,
                consume_usage: bool,
            },
            RealtimeTranscriptSnapshotRestoreAuthorized,

            // Durable-config region effects. Each is a fieldless authorization
            // marker: the admission verdict is the machine's decision (a
            // rejected request matches no transition and surfaces as `Err`).
            // The original typed `SessionMetadata` / `SessionBuildState` /
            // prompt value is carried through unchanged by the meerkat-core
            // shell wrapper — there is nothing for the machine to echo, so no
            // fact is dead-carried back across the seam.
            SessionMetadataPersistAuthorized,
            SessionBuildStatePersistAuthorized,
            SessionBuildStateRestoreAuthorized,
            SystemPromptMutationAuthorized,

            // Pending-continuation region effects. The disposition is the
            // machine's decision; the shell mirrors it onto its run-pending /
            // start-turn-disposition path and decides nothing. The public
            // terminal witness is emitted alongside `NoPendingBoundary` so the
            // shell can surface the typed terminal without re-deriving it.
            PendingContinuationResolved { disposition: Enum<PendingContinuationDisposition> },
            PendingContinuationPublicTerminalResolved { terminal: Enum<PendingContinuationPublicTerminal> },

            // Resume-override-admission region effects. On accept the machine
            // emits the verdict alongside the effective LLM-binding selection
            // (provider source, self-hosted source, provider_overridden flag);
            // the shell mirrors the selection and decides nothing. On reject the
            // machine emits the typed rejection reason; the shell maps it to its
            // typed recovery error.
            SessionResumeOverridesAuthorized {
                provider_selection: Enum<ResumeProviderSelection>,
                self_hosted_selection: Enum<ResumeSelfHostedSelection>,
                provider_overridden: bool,
            },
            SessionResumeOverridesRejected { reason: Enum<ResumeOverrideRejection> },

            // Live-vs-durable session-document authority verdict. The shell
            // mirrors `authority`: LiveAuthoritative keeps the live document;
            // DurableAuthoritative supersedes it with the stored document and
            // carries the typed precedence `reason`. On LiveAuthoritative the
            // emitted `reason` is a placeholder the shell must ignore.
            LiveSessionAuthorityClassified {
                authority: Enum<LiveSessionAuthorityKind>,
                reason: Enum<LiveSessionAuthorityReason>,
            },

            // Recovery-source-projection verdict (KEYSTONE). The shell mirrors
            // `recoverable`: true -> the store projection is an authoritative
            // read source; false -> it is not (fall through to quarantine /
            // `None`). This is a total verdict over the two typed presence
            // observations, so it is emitted on both branches (never a
            // no-match) — a store-only session that legitimately carries no
            // metadata or build state resolves to `recoverable: false`
            // explicitly rather than silently failing to load.
            SessionStoreRecoverySourceResolved { recoverable: bool },

            // Runtime-projection-rollback disposition. The shell mirrors
            // `disposition`: RebuildToAuthority authorizes the CAS projection
            // write that converges the ahead-of-authority row back onto the
            // committed transcript; RejectDivergent keeps the fail-closed
            // rejection for genuine content forks. Total over the observation,
            // so it is emitted on both branches.
            RuntimeProjectionRollbackResolved {
                disposition: Enum<RuntimeProjectionRollbackDisposition>,
            },

            // Apply-pending-tool-results verdict. The shell mirrors
            // `applied_count` onto its `agent.apply_pending_tool_results` call:
            // it applies exactly the machine-authorized count. The verdict is
            // vacuous-accept (it mirrors the consumed count), matching the
            // staging-side `SessionToolResultsStageResolved` shape.
            SessionToolResultsApplied {
                session_id: SessionId,
                applied_count: u64,
            },

            // Transcript-edit commit verdict. The shell mirrors `success` onto
            // its persist path: it commits the fork/rewrite only after the
            // machine authorizes it. The typed `kind` echoes the authorized
            // directive so the shell routes to the correct persist handler
            // without re-deriving it.
            TranscriptRewriteCommitted {
                kind: Enum<TranscriptEditKind>,
                success: bool,
            },

            // Lifecycle-terminal region effects. The recover marker witnesses
            // the registry adoption; the archive verdict carries the
            // disposition plus the realization action vector. The shell
            // realizes the vector fail-closed and IN ORDER — durable document
            // commit first, runtime retire second — and decides nothing: a
            // realization failure surfaces as the archive operation's error
            // with durable truth still convergent (`Retired` implies the
            // document is Archived; the converse failure window is retryable).
            SessionLifecycleTerminalRecovered,
            SessionArchiveResolved {
                disposition: Enum<SessionArchiveDisposition>,
                write_document: bool,
                retire_runtime: bool,
            },
        }

        helper phase_allows_initial_turn_overrides(phase: Enum<SessionFirstTurnPhase>) -> bool {
            phase == SessionFirstTurnPhase::Pending
        }

        helper should_store_initial_prompt(
            phase: Enum<SessionFirstTurnPhase>,
            prompt_has_content: bool
        ) -> bool {
            phase == SessionFirstTurnPhase::Pending && prompt_has_content
        }

        // System-context append classification helpers (ported verbatim from
        // the retired SessionSystemContextAuthorityMachine).
        helper append_is_empty(trimmed_text_byte_count: u64) -> bool {
            trimmed_text_byte_count == 0
        }

        helper append_is_conflict(
            idempotency_key_present: bool,
            existing_key_conflicts: bool
        ) -> bool {
            idempotency_key_present && existing_key_conflicts
        }

        helper append_is_duplicate(
            idempotency_key_present: bool,
            existing_key_matches: bool,
            existing_key_conflicts: bool
        ) -> bool {
            idempotency_key_present && existing_key_matches && existing_key_conflicts == false
        }

        helper append_is_new(
            idempotency_key_present: bool,
            existing_key_matches: bool,
            existing_key_conflicts: bool
        ) -> bool {
            idempotency_key_present == false
                || (existing_key_matches == false && existing_key_conflicts == false)
        }

        // Persist-time append-admission verdict. Admissible iff the incoming
        // persisted prompt is either a byte-identical no-op refresh of an
        // existing prompt, OR a prefix-preserving append (separator-delimited)
        // carrying the typed runtime-context-append provenance, OR — when there
        // is no previous prompt — itself a typed runtime-context-append. Every
        // other shape is rejected. Mirrors the retired
        // `system_context_is_append` shell reducer exactly.
        helper persist_append_is_admissible(
            has_previous: bool,
            content_identical: bool,
            content_extends_previous: bool,
            appended_starts_with_separator: bool,
            incoming_is_runtime_context_append: bool
        ) -> bool {
            (has_previous && content_identical)
                || (has_previous
                    && content_extends_previous
                    && appended_starts_with_separator
                    && incoming_is_runtime_context_append)
                || (has_previous == false && incoming_is_runtime_context_append)
        }

        // Realtime-transcript region classification helpers (ported verbatim
        // from the retired SessionRealtimeTranscriptAuthorityMachine).
        helper realtime_delta_is_duplicate(delta_id_present: bool, delta_id_seen: bool) -> bool {
            delta_id_present && delta_id_seen
        }

        helper realtime_lane_accepts(
            item_has_text: bool,
            current_lane: Enum<RealtimeTranscriptLaneKind>,
            requested_lane: Enum<RealtimeTranscriptLaneKind>
        ) -> bool {
            current_lane == requested_lane || item_has_text == false
        }

        helper realtime_should_mark_ready_after_write(
            response_completed: bool,
            text_after_write_present: bool
        ) -> bool {
            response_completed && text_after_write_present
        }

        helper realtime_stop_reason_discards(
            stop_reason: Enum<RealtimeTranscriptStopReasonKind>
        ) -> bool {
            stop_reason == RealtimeTranscriptStopReasonKind::Cancelled
        }

        helper realtime_stop_reason_removes_completion(
            stop_reason: Enum<RealtimeTranscriptStopReasonKind>
        ) -> bool {
            stop_reason == RealtimeTranscriptStopReasonKind::ToolUse
        }

        helper realtime_stop_reason_records_completion(
            stop_reason: Enum<RealtimeTranscriptStopReasonKind>
        ) -> bool {
            stop_reason == RealtimeTranscriptStopReasonKind::Other
        }

        // Pending-continuation classification helpers (ported verbatim from the
        // retired PendingContinuationAdmissionMachine). A `User` or `ToolResults`
        // tail is itself a runnable continuation boundary; staged tool results
        // are a boundary even when the tail is something else.
        helper tail_has_pending_boundary(session_tail: Enum<ObservedSessionTailKind>) -> bool {
            session_tail == ObservedSessionTailKind::User
                || session_tail == ObservedSessionTailKind::ToolResults
        }

        helper has_effective_pending_boundary(
            session_tail: Enum<ObservedSessionTailKind>,
            staged_tool_result_count: u64
        ) -> bool {
            tail_has_pending_boundary(session_tail) || staged_tool_result_count > 0
        }

        // Resume-override-admission classification helpers (folded from the
        // handwritten session_recovery.rs shell). Each reject condition is the
        // verbatim port of the corresponding shell `if` guard; the LLM-binding
        // selection helpers port `resolve_resume_llm_binding`.
        helper resume_reject_provider_requires_model(
            provider_override_present: bool,
            model_override_present: bool
        ) -> bool {
            provider_override_present && model_override_present == false
        }

        helper resume_reject_build_only_after_first_turn(
            has_build_only_overrides: bool,
            first_turn_phase: Enum<SessionFirstTurnPhase>
        ) -> bool {
            has_build_only_overrides
                && phase_allows_initial_turn_overrides(first_turn_phase) == false
        }

        // A resume request is admissible iff neither reject condition fires.
        // Used as the guard prefix for every accept branch. The illegal
        // "clear + set" provider_params/auth_binding fourth state is no longer
        // representable at the shell seam (it carries a single
        // `Option<TurnMetadataOverride<T>>`), so the machine no longer observes
        // or rejects it.
        helper resume_overrides_admissible(
            provider_override_present: bool,
            model_override_present: bool,
            has_build_only_overrides: bool,
            first_turn_phase: Enum<SessionFirstTurnPhase>
        ) -> bool {
            resume_reject_provider_requires_model(
                provider_override_present,
                model_override_present
            ) == false
            && resume_reject_build_only_after_first_turn(
                has_build_only_overrides,
                first_turn_phase
            ) == false
        }

        // Provider selection (port of resolve_resume_llm_binding): a model
        // change without an explicit provider override recomputes the provider
        // from the new model; an explicit provider override is used directly;
        // otherwise the stored provider is retained.
        helper resume_provider_recompute_from_model(
            model_override_present: bool,
            provider_override_present: bool
        ) -> bool {
            model_override_present && provider_override_present == false
        }

        // Recovery-source-projection predicate (port of the retired shell
        // `runtime_backed_store_projection_can_recover_authority`): a persisted
        // store projection is a valid authoritative read source iff it carries
        // canonical session metadata, build state, OR a generated runtime
        // projection quarantine fact.
        helper store_projection_can_recover_authority(
            has_metadata: bool,
            has_build_state: bool,
            runtime_projection_quarantined: bool
        ) -> bool {
            has_metadata || has_build_state || runtime_projection_quarantined
        }

        // Lifecycle-terminal realization helper: the runtime is retired iff
        // the archive is runtime-backed AND the session is actually known to
        // the runtime side (a durable snapshot exists or the runtime has the
        // session registered). A runtime-backed archive of a session the
        // runtime has never seen must not spuriously register-then-retire it.
        helper archive_should_retire_runtime(
            runtime_backed: bool,
            durable_snapshot_present: bool,
            runtime_session_registered: bool
        ) -> bool {
            runtime_backed && (durable_snapshot_present || runtime_session_registered)
        }

        disposition SessionFirstTurnPhaseResolved => local seam NoOwnerRealization,
        disposition SessionFirstTurnOverridesResolved => local seam NoOwnerRealization,
        disposition SessionInitialPromptStageResolved => local seam NoOwnerRealization,
        disposition SessionToolResultsStageResolved => local seam NoOwnerRealization,
        disposition SessionConsumedInputsRestoreResolved => local seam NoOwnerRealization,
        disposition SessionFirstTurnPhaseRecovered => local seam NoOwnerRealization,
        disposition SystemContextAppendResolved => local seam NoOwnerRealization,
        disposition SystemContextPendingApplyItemResolved => local seam NoOwnerRealization,
        disposition SystemContextSteerCleanupItemResolved => local seam NoOwnerRealization,
        disposition SystemContextSnapshotRestoreAuthorized => local seam NoOwnerRealization,
        disposition SystemContextPersistAppendAdmissionResolved => local seam NoOwnerRealization,
        disposition RealtimeTranscriptEventResolved => local seam NoOwnerRealization,
        disposition RealtimeMaterializeCandidateResolved => local seam NoOwnerRealization,
        disposition RealtimeTranscriptSnapshotRestoreAuthorized => local seam NoOwnerRealization,
        disposition SessionMetadataPersistAuthorized => local seam NoOwnerRealization,
        disposition SessionBuildStatePersistAuthorized => local seam NoOwnerRealization,
        disposition SessionBuildStateRestoreAuthorized => local seam NoOwnerRealization,
        disposition SystemPromptMutationAuthorized => local seam NoOwnerRealization,
        disposition PendingContinuationResolved => local seam NoOwnerRealization,
        disposition PendingContinuationPublicTerminalResolved => local seam NoOwnerRealization,
        disposition SessionResumeOverridesAuthorized => local seam NoOwnerRealization,
        disposition SessionResumeOverridesRejected => local seam NoOwnerRealization,
        disposition LiveSessionAuthorityClassified => local seam NoOwnerRealization,
        disposition SessionStoreRecoverySourceResolved => local seam NoOwnerRealization,
        disposition RuntimeProjectionRollbackResolved => local seam NoOwnerRealization,
        disposition SessionToolResultsApplied => local seam NoOwnerRealization,
        disposition TranscriptRewriteCommitted => local seam NoOwnerRealization,
        disposition SessionLifecycleTerminalRecovered => local seam NoOwnerRealization,
        disposition SessionArchiveResolved => local seam NoOwnerRealization,

        // ---------------------------------------------------------------
        // MarkSessionInitialTurnPending
        //
        // Old legality (MarkInitialTurnPending): Inactive|Pending -> Pending
        // emit was_pending=false; Consumed stays Consumed emit was_pending=false.
        // ---------------------------------------------------------------
        transition MarkSessionInitialTurnPendingInactiveOrPending {
            on input MarkSessionInitialTurnPending { session_id }
            guard {
                self.lifecycle_phase == Phase::Ready
                && (self.session_first_turn_phase.get_cloned(session_id).get("value")
                        == SessionFirstTurnPhase::Inactive
                    || self.session_first_turn_phase.get_cloned(session_id).get("value")
                        == SessionFirstTurnPhase::Pending)
            }
            update {
                self.session_first_turn_phase.insert(session_id, SessionFirstTurnPhase::Pending);
            }
            to Ready
            emit SessionFirstTurnPhaseResolved {
                phase: SessionFirstTurnPhase::Pending,
                was_pending: false
            }
        }

        transition MarkSessionInitialTurnPendingConsumed {
            on input MarkSessionInitialTurnPending { session_id }
            guard {
                self.lifecycle_phase == Phase::Ready
                && self.session_first_turn_phase.get_cloned(session_id).get("value")
                    == SessionFirstTurnPhase::Consumed
            }
            update {}
            to Ready
            emit SessionFirstTurnPhaseResolved {
                phase: SessionFirstTurnPhase::Consumed,
                was_pending: false
            }
        }

        // ---------------------------------------------------------------
        // StartSessionInitialTurn
        //
        // Old legality (StartInitialTurn): Pending -> Consumed emit
        // was_pending=true (load-bearing for rollback); Inactive stays
        // Inactive emit was_pending=false; Consumed stays Consumed emit
        // was_pending=false. `Consumed` is the absorbing phase.
        // ---------------------------------------------------------------
        transition StartSessionInitialTurnPending {
            on input StartSessionInitialTurn { session_id }
            guard {
                self.lifecycle_phase == Phase::Ready
                && self.session_first_turn_phase.get_cloned(session_id).get("value")
                    == SessionFirstTurnPhase::Pending
            }
            update {
                self.session_first_turn_phase.insert(session_id, SessionFirstTurnPhase::Consumed);
            }
            to Ready
            emit SessionFirstTurnPhaseResolved {
                phase: SessionFirstTurnPhase::Consumed,
                was_pending: true
            }
        }

        transition StartSessionInitialTurnInactive {
            on input StartSessionInitialTurn { session_id }
            guard {
                self.lifecycle_phase == Phase::Ready
                && self.session_first_turn_phase.get_cloned(session_id).get("value")
                    == SessionFirstTurnPhase::Inactive
            }
            update {}
            to Ready
            emit SessionFirstTurnPhaseResolved {
                phase: SessionFirstTurnPhase::Inactive,
                was_pending: false
            }
        }

        transition StartSessionInitialTurnConsumed {
            on input StartSessionInitialTurn { session_id }
            guard {
                self.lifecycle_phase == Phase::Ready
                && self.session_first_turn_phase.get_cloned(session_id).get("value")
                    == SessionFirstTurnPhase::Consumed
            }
            update {}
            to Ready
            emit SessionFirstTurnPhaseResolved {
                phase: SessionFirstTurnPhase::Consumed,
                was_pending: false
            }
        }

        // ---------------------------------------------------------------
        // ResolveSessionFirstTurnOverridesAllowed
        //
        // Old legality (AllowsInitialTurnOverrides): allowed == (phase == Pending).
        // ---------------------------------------------------------------
        transition ResolveSessionFirstTurnOverridesAllowed {
            on input ResolveSessionFirstTurnOverridesAllowed { session_id }
            guard {
                self.lifecycle_phase == Phase::Ready
                && phase_allows_initial_turn_overrides(
                    self.session_first_turn_phase.get_cloned(session_id).get("value")
                )
            }
            update {}
            to Ready
            emit SessionFirstTurnOverridesResolved { allowed: true }
        }

        transition ResolveSessionFirstTurnOverridesDenied {
            on input ResolveSessionFirstTurnOverridesAllowed { session_id }
            guard {
                self.lifecycle_phase == Phase::Ready
                && phase_allows_initial_turn_overrides(
                    self.session_first_turn_phase.get_cloned(session_id).get("value")
                ) == false
            }
            update {}
            to Ready
            emit SessionFirstTurnOverridesResolved { allowed: false }
        }

        // ---------------------------------------------------------------
        // StageSessionInitialPrompt
        //
        // Old legality (ResolveInitialPromptStage): Store iff phase == Pending
        // && prompt_has_content; else Clear. The machine also tracks
        // presence in its own state for recovery legality.
        // ---------------------------------------------------------------
        transition StageSessionInitialPromptStore {
            on input StageSessionInitialPrompt { session_id, prompt_has_content }
            guard {
                self.lifecycle_phase == Phase::Ready
                && should_store_initial_prompt(
                    self.session_first_turn_phase.get_cloned(session_id).get("value"),
                    prompt_has_content
                )
            }
            update {
                self.session_pending_initial_prompt_present.insert(session_id, true);
            }
            to Ready
            emit SessionInitialPromptStageResolved {
                decision: SessionInitialPromptStageDecision::Store
            }
        }

        transition StageSessionInitialPromptClear {
            on input StageSessionInitialPrompt { session_id, prompt_has_content }
            guard {
                self.lifecycle_phase == Phase::Ready
                && should_store_initial_prompt(
                    self.session_first_turn_phase.get_cloned(session_id).get("value"),
                    prompt_has_content
                ) == false
            }
            update {
                self.session_pending_initial_prompt_present.insert(session_id, false);
            }
            to Ready
            emit SessionInitialPromptStageResolved {
                decision: SessionInitialPromptStageDecision::Clear
            }
        }

        // ---------------------------------------------------------------
        // StageSessionToolResults
        //
        // Old legality (ResolveToolResultsStage): vacuously accepts in every
        // phase, emitting accepted_count == result_count. The machine tracks
        // the count in its own state for recovery legality.
        // ---------------------------------------------------------------
        transition StageSessionToolResults {
            on input StageSessionToolResults { session_id, result_count }
            guard {
                self.lifecycle_phase == Phase::Ready
                && (self.session_first_turn_phase.get_cloned(session_id).get("value")
                        == SessionFirstTurnPhase::Inactive
                    || self.session_first_turn_phase.get_cloned(session_id).get("value")
                        == SessionFirstTurnPhase::Pending
                    || self.session_first_turn_phase.get_cloned(session_id).get("value")
                        == SessionFirstTurnPhase::Consumed)
            }
            update {
                self.session_pending_tool_results_count.insert(session_id, result_count);
            }
            to Ready
            emit SessionToolResultsStageResolved { accepted_count: result_count }
        }

        // ---------------------------------------------------------------
        // ConsumeSessionDeferredInputs
        //
        // Old legality: consuming a started turn is `StartInitialTurn`
        // (Pending -> Consumed emit was_pending=true) followed by clearing
        // the bulky payload mirrors. The shell takes the actual payloads;
        // the machine clears its presence/count mirrors and absorbs the
        // first-turn phase.
        // ---------------------------------------------------------------
        transition ConsumeSessionDeferredInputsPending {
            on input ConsumeSessionDeferredInputs { session_id }
            guard {
                self.lifecycle_phase == Phase::Ready
                && self.session_first_turn_phase.get_cloned(session_id).get("value")
                    == SessionFirstTurnPhase::Pending
            }
            update {
                self.session_first_turn_phase.insert(session_id, SessionFirstTurnPhase::Consumed);
                self.session_pending_initial_prompt_present.insert(session_id, false);
                self.session_pending_tool_results_count.insert(session_id, 0);
            }
            to Ready
            emit SessionFirstTurnPhaseResolved {
                phase: SessionFirstTurnPhase::Consumed,
                was_pending: true
            }
        }

        transition ConsumeSessionDeferredInputsInactive {
            on input ConsumeSessionDeferredInputs { session_id }
            guard {
                self.lifecycle_phase == Phase::Ready
                && self.session_first_turn_phase.get_cloned(session_id).get("value")
                    == SessionFirstTurnPhase::Inactive
            }
            update {
                self.session_pending_initial_prompt_present.insert(session_id, false);
                self.session_pending_tool_results_count.insert(session_id, 0);
            }
            to Ready
            emit SessionFirstTurnPhaseResolved {
                phase: SessionFirstTurnPhase::Inactive,
                was_pending: false
            }
        }

        transition ConsumeSessionDeferredInputsConsumed {
            on input ConsumeSessionDeferredInputs { session_id }
            guard {
                self.lifecycle_phase == Phase::Ready
                && self.session_first_turn_phase.get_cloned(session_id).get("value")
                    == SessionFirstTurnPhase::Consumed
            }
            update {
                self.session_pending_initial_prompt_present.insert(session_id, false);
                self.session_pending_tool_results_count.insert(session_id, 0);
            }
            to Ready
            emit SessionFirstTurnPhaseResolved {
                phase: SessionFirstTurnPhase::Consumed,
                was_pending: false
            }
        }

        // ---------------------------------------------------------------
        // RestoreSessionConsumedInputs
        //
        // Old legality (ResolveConsumedInputsRestore): vacuously authorizes,
        // emitting restore_initial_prompt == pending_initial_prompt_present
        // and restore_tool_results == (pending_tool_result_message_count > 0).
        // On a Consumed session that is being rolled back to Pending, restore
        // the machine-owned phase + presence/count mirrors.
        // ---------------------------------------------------------------
        transition RestoreSessionConsumedInputs {
            on input RestoreSessionConsumedInputs {
                session_id,
                restore_first_turn_pending,
                pending_initial_prompt_present,
                pending_tool_result_message_count
            }
            guard { self.lifecycle_phase == Phase::Ready && restore_first_turn_pending }
            update {
                self.session_first_turn_phase.insert(session_id, SessionFirstTurnPhase::Pending);
                self.session_pending_initial_prompt_present
                    .insert(session_id, pending_initial_prompt_present);
                self.session_pending_tool_results_count
                    .insert(session_id, pending_tool_result_message_count);
            }
            to Ready
            emit SessionConsumedInputsRestoreResolved {
                restore_first_turn_pending: restore_first_turn_pending,
                restore_initial_prompt: pending_initial_prompt_present,
                restore_tool_results: pending_tool_result_message_count > 0
            }
        }

        transition RestoreSessionConsumedInputsNoPhaseRollback {
            on input RestoreSessionConsumedInputs {
                session_id,
                restore_first_turn_pending,
                pending_initial_prompt_present,
                pending_tool_result_message_count
            }
            guard { self.lifecycle_phase == Phase::Ready && restore_first_turn_pending == false }
            update {
                self.session_pending_initial_prompt_present
                    .insert(session_id, pending_initial_prompt_present);
                self.session_pending_tool_results_count
                    .insert(session_id, pending_tool_result_message_count);
            }
            to Ready
            emit SessionConsumedInputsRestoreResolved {
                restore_first_turn_pending: restore_first_turn_pending,
                restore_initial_prompt: pending_initial_prompt_present,
                restore_tool_results: pending_tool_result_message_count > 0
            }
        }

        // ---------------------------------------------------------------
        // RecoverSessionFirstTurnPhase
        //
        // Old legality (RestoreDeferredTurnState): authorize a durable
        // snapshot restore for any first-turn phase, then adopt the restored
        // phase + presence/count into the machine-owned registry.
        // ---------------------------------------------------------------
        transition RecoverSessionFirstTurnPhase {
            on input RecoverSessionFirstTurnPhase {
                session_id,
                phase,
                pending_initial_prompt_present,
                pending_tool_result_message_count
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && (phase == SessionFirstTurnPhase::Inactive
                    || phase == SessionFirstTurnPhase::Pending
                    || phase == SessionFirstTurnPhase::Consumed)
            }
            update {
                self.session_first_turn_phase.insert(session_id, phase);
                self.session_pending_initial_prompt_present
                    .insert(session_id, pending_initial_prompt_present);
                self.session_pending_tool_results_count
                    .insert(session_id, pending_tool_result_message_count);
            }
            to Ready
            emit SessionFirstTurnPhaseRecovered
        }

        // ===============================================================
        // System-context region (folded from the retired
        // SessionSystemContextAuthorityMachine).
        // ===============================================================

        // ---------------------------------------------------------------
        // ResolveSystemContextAppend — four-way append disposition.
        //
        // Ported verbatim from the retired ResolveAppend transitions. The
        // observations (key present / matches / conflicts) are mechanical
        // string-equality facts the shell computes against its bulky `seen`
        // map; the SEMANTIC disposition is decided here from those typed
        // observations via the append classification helpers.
        // ---------------------------------------------------------------
        transition ResolveSystemContextAppendEmpty {
            on input ResolveSystemContextAppend {
                trimmed_text_byte_count,
                idempotency_key_present,
                existing_key_matches,
                existing_key_conflicts,
                active_turn_scoped
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && append_is_empty(trimmed_text_byte_count)
            }
            update {}
            to Ready
            emit SystemContextAppendResolved {
                decision: SystemContextAppendDecision::RejectEmpty,
                active_turn_scoped: active_turn_scoped
            }
        }

        transition ResolveSystemContextAppendConflict {
            on input ResolveSystemContextAppend {
                trimmed_text_byte_count,
                idempotency_key_present,
                existing_key_matches,
                existing_key_conflicts,
                active_turn_scoped
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && append_is_empty(trimmed_text_byte_count) == false
                && append_is_conflict(idempotency_key_present, existing_key_conflicts)
            }
            update {}
            to Ready
            emit SystemContextAppendResolved {
                decision: SystemContextAppendDecision::RejectConflict,
                active_turn_scoped: active_turn_scoped
            }
        }

        transition ResolveSystemContextAppendDuplicate {
            on input ResolveSystemContextAppend {
                trimmed_text_byte_count,
                idempotency_key_present,
                existing_key_matches,
                existing_key_conflicts,
                active_turn_scoped
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && append_is_empty(trimmed_text_byte_count) == false
                && append_is_duplicate(
                    idempotency_key_present,
                    existing_key_matches,
                    existing_key_conflicts)
            }
            update {}
            to Ready
            emit SystemContextAppendResolved {
                decision: SystemContextAppendDecision::Duplicate,
                active_turn_scoped: active_turn_scoped
            }
        }

        transition ResolveSystemContextAppendNew {
            on input ResolveSystemContextAppend {
                trimmed_text_byte_count,
                idempotency_key_present,
                existing_key_matches,
                existing_key_conflicts,
                active_turn_scoped
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && append_is_empty(trimmed_text_byte_count) == false
                && append_is_new(
                    idempotency_key_present,
                    existing_key_matches,
                    existing_key_conflicts)
            }
            update {}
            to Ready
            emit SystemContextAppendResolved {
                decision: SystemContextAppendDecision::Staged,
                active_turn_scoped: active_turn_scoped
            }
        }

        // ---------------------------------------------------------------
        // ResolveSystemContextPersistAppendAdmission — persist-time
        // append-admission continuity verdict for the session-store atomic
        // append-only save guard. The shell extracts the structural prefix
        // observations plus the typed runtime-context-append provenance; this
        // machine owns the Admit/Reject verdict via persist_append_is_admissible.
        // ---------------------------------------------------------------
        transition ResolveSystemContextPersistAppendAdmissionAdmit {
            on input ResolveSystemContextPersistAppendAdmission {
                has_previous,
                content_identical,
                content_extends_previous,
                appended_starts_with_separator,
                incoming_is_runtime_context_append
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && persist_append_is_admissible(
                    has_previous,
                    content_identical,
                    content_extends_previous,
                    appended_starts_with_separator,
                    incoming_is_runtime_context_append)
            }
            update {}
            to Ready
            emit SystemContextPersistAppendAdmissionResolved {
                admission: SystemContextPersistAppendAdmission::Admit
            }
        }

        transition ResolveSystemContextPersistAppendAdmissionReject {
            on input ResolveSystemContextPersistAppendAdmission {
                has_previous,
                content_identical,
                content_extends_previous,
                appended_starts_with_separator,
                incoming_is_runtime_context_append
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && persist_append_is_admissible(
                    has_previous,
                    content_identical,
                    content_extends_previous,
                    appended_starts_with_separator,
                    incoming_is_runtime_context_append) == false
            }
            update {}
            to Ready
            emit SystemContextPersistAppendAdmissionResolved {
                admission: SystemContextPersistAppendAdmission::Reject
            }
        }

        // ---------------------------------------------------------------
        // ResolveSystemContextPendingApplyItem — per-pending-append apply
        // decision. Guards the TYPED source_kind: a runtime-steer append is
        // dropped from the applied set and its seen entry removed; a normal
        // append is promoted to applied and its seen entry marked applied.
        //
        // This replaces the retired `is_runtime_steer_append` string-prefix
        // classification (`source.starts_with("runtime:steer:")`).
        // ---------------------------------------------------------------
        transition ResolveSystemContextPendingApplyItemRuntimeSteer {
            on input ResolveSystemContextPendingApplyItem { source_kind }
            guard {
                self.lifecycle_phase == Phase::Ready
                && source_kind == SystemContextSource::RuntimeSteer
            }
            update {}
            to Ready
            emit SystemContextPendingApplyItemResolved {
                promote_to_applied: false,
                mark_seen_applied: false,
                remove_seen: true
            }
        }

        transition ResolveSystemContextPendingApplyItemNormal {
            on input ResolveSystemContextPendingApplyItem { source_kind }
            guard {
                self.lifecycle_phase == Phase::Ready
                && source_kind == SystemContextSource::Normal
            }
            update {}
            to Ready
            emit SystemContextPendingApplyItemResolved {
                promote_to_applied: true,
                mark_seen_applied: true,
                remove_seen: false
            }
        }

        // ---------------------------------------------------------------
        // ResolveSystemContextSteerCleanupItem — per-item transient-steer
        // discard decision, guarding the typed source_kind.
        // ---------------------------------------------------------------
        transition ResolveSystemContextSteerCleanupItemRuntimeSteer {
            on input ResolveSystemContextSteerCleanupItem { source_kind }
            guard {
                self.lifecycle_phase == Phase::Ready
                && source_kind == SystemContextSource::RuntimeSteer
            }
            update {}
            to Ready
            emit SystemContextSteerCleanupItemResolved { discard: true }
        }

        transition ResolveSystemContextSteerCleanupItemNormal {
            on input ResolveSystemContextSteerCleanupItem { source_kind }
            guard {
                self.lifecycle_phase == Phase::Ready
                && source_kind == SystemContextSource::Normal
            }
            update {}
            to Ready
            emit SystemContextSteerCleanupItemResolved { discard: false }
        }

        // ---------------------------------------------------------------
        // RestoreSystemContextSnapshot — snapshot-restore consistency
        // authorization, ported verbatim from AuthorizeRestoreSystemContextState.
        // ---------------------------------------------------------------
        transition RestoreSystemContextSnapshot {
            on input RestoreSystemContextSnapshot {
                active_keys_have_known_pending_or_seen,
                seen_keys_match_known_appends
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && active_keys_have_known_pending_or_seen
                && seen_keys_match_known_appends
            }
            update {}
            to Ready
            emit SystemContextSnapshotRestoreAuthorized
        }

        // ===============================================================
        // Realtime-transcript region (folded from the retired
        // SessionRealtimeTranscriptAuthorityMachine). Each transition is a
        // verbatim port: it reads only the typed RAW observations carried on
        // the input and resolves the action vector / materialize verdict.
        // The shell mirrors the emitted decision onto its bulky
        // `SessionRealtimeTranscriptState` and decides nothing.
        // ===============================================================

        transition ResolveRealtimeItemObservedDiscardedAssistant {
            on input ResolveRealtimeItemObserved { role, response_discarded }
            guard {
                self.lifecycle_phase == Phase::Ready
                && role == RealtimeTranscriptRoleKind::Assistant
                && response_discarded
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: true,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeItemObservedPresent {
            on input ResolveRealtimeItemObserved { role, response_discarded }
            guard {
                self.lifecycle_phase == Phase::Ready
                && (role != RealtimeTranscriptRoleKind::Assistant || response_discarded == false)
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: true,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeItemSkipped {
            on input ResolveRealtimeItemSkipped
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: true,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeUserTranscriptFinalEmpty {
            on input ResolveRealtimeUserTranscriptFinal { text_present, segment_empty, segment_matches }
            guard {
                self.lifecycle_phase == Phase::Ready
                && text_present == false
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: true,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: true,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeUserTranscriptFinalStore {
            on input ResolveRealtimeUserTranscriptFinal { text_present, segment_empty, segment_matches }
            guard {
                self.lifecycle_phase == Phase::Ready
                && text_present
                && segment_empty
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: true,
                observe_skipped: false,
                write_user_segment: true,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: true,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeUserTranscriptFinalReplayOrConflict {
            on input ResolveRealtimeUserTranscriptFinal { text_present, segment_empty, segment_matches }
            guard {
                self.lifecycle_phase == Phase::Ready
                && text_present
                && segment_empty == false
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: true,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: true,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeAssistantDeltaInvalidOrDuplicate {
            on input ResolveRealtimeAssistantDelta {
                response_id_valid,
                response_discarded,
                delta_id_present,
                delta_id_seen,
                item_has_text,
                current_lane,
                requested_lane,
                response_completed,
                text_after_write_present
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && (response_id_valid == false
                    || realtime_delta_is_duplicate(delta_id_present, delta_id_seen))
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: false
            }
        }

        transition ResolveRealtimeAssistantDeltaDiscarded {
            on input ResolveRealtimeAssistantDelta {
                response_id_valid,
                response_discarded,
                delta_id_present,
                delta_id_seen,
                item_has_text,
                current_lane,
                requested_lane,
                response_completed,
                text_after_write_present
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid
                && response_discarded
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: true,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeAssistantDeltaLaneConflict {
            on input ResolveRealtimeAssistantDelta {
                response_id_valid,
                response_discarded,
                delta_id_present,
                delta_id_seen,
                item_has_text,
                current_lane,
                requested_lane,
                response_completed,
                text_after_write_present
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid
                && response_discarded == false
                && realtime_delta_is_duplicate(delta_id_present, delta_id_seen) == false
                && realtime_lane_accepts(item_has_text, current_lane, requested_lane) == false
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: true,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: delta_id_present,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeAssistantDeltaAccepted {
            on input ResolveRealtimeAssistantDelta {
                response_id_valid,
                response_discarded,
                delta_id_present,
                delta_id_seen,
                item_has_text,
                current_lane,
                requested_lane,
                response_completed,
                text_after_write_present
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid
                && response_discarded == false
                && realtime_delta_is_duplicate(delta_id_present, delta_id_seen) == false
                && realtime_lane_accepts(item_has_text, current_lane, requested_lane)
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: true,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: true,
                replace_assistant_segment: false,
                promote_lane: true,
                mark_item_ready: realtime_should_mark_ready_after_write(response_completed, text_after_write_present),
                record_delta_id: delta_id_present,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeAssistantReplacementInvalid {
            on input ResolveRealtimeAssistantTextReplacement {
                response_id_valid,
                response_discarded,
                item_materialized,
                item_has_text,
                current_lane,
                requested_lane,
                response_completed,
                text_after_replace_present
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid == false
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: false
            }
        }

        transition ResolveRealtimeAssistantReplacementDiscarded {
            on input ResolveRealtimeAssistantTextReplacement {
                response_id_valid,
                response_discarded,
                item_materialized,
                item_has_text,
                current_lane,
                requested_lane,
                response_completed,
                text_after_replace_present
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid
                && response_discarded
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: true,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeAssistantReplacementLocked {
            on input ResolveRealtimeAssistantTextReplacement {
                response_id_valid,
                response_discarded,
                item_materialized,
                item_has_text,
                current_lane,
                requested_lane,
                response_completed,
                text_after_replace_present
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid
                && response_discarded == false
                && item_materialized
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: true,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeAssistantReplacementLaneConflict {
            on input ResolveRealtimeAssistantTextReplacement {
                response_id_valid,
                response_discarded,
                item_materialized,
                item_has_text,
                current_lane,
                requested_lane,
                response_completed,
                text_after_replace_present
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid
                && response_discarded == false
                && item_materialized == false
                && realtime_lane_accepts(item_has_text, current_lane, requested_lane) == false
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: true,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeAssistantReplacementAccepted {
            on input ResolveRealtimeAssistantTextReplacement {
                response_id_valid,
                response_discarded,
                item_materialized,
                item_has_text,
                current_lane,
                requested_lane,
                response_completed,
                text_after_replace_present
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid
                && response_discarded == false
                && item_materialized == false
                && realtime_lane_accepts(item_has_text, current_lane, requested_lane)
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: true,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: true,
                promote_lane: true,
                mark_item_ready: realtime_should_mark_ready_after_write(response_completed, text_after_replace_present),
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeAssistantTurnCompletedInvalid {
            on input ResolveRealtimeAssistantTurnCompleted { response_id_valid, response_discarded, stop_reason }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid == false
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: false
            }
        }

        transition ResolveRealtimeAssistantTurnCompletedDiscard {
            on input ResolveRealtimeAssistantTurnCompleted { response_id_valid, response_discarded, stop_reason }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid
                && (response_discarded || realtime_stop_reason_discards(stop_reason))
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: true,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeAssistantTurnCompletedToolUse {
            on input ResolveRealtimeAssistantTurnCompleted { response_id_valid, response_discarded, stop_reason }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid
                && response_discarded == false
                && realtime_stop_reason_removes_completion(stop_reason)
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: true,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeAssistantTurnCompletedRecord {
            on input ResolveRealtimeAssistantTurnCompleted { response_id_valid, response_discarded, stop_reason }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid
                && response_discarded == false
                && realtime_stop_reason_records_completion(stop_reason)
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: true,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: true,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeAssistantTurnInterruptedInvalid {
            on input ResolveRealtimeAssistantTurnInterrupted { response_id_valid }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid == false
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: false,
                discard_response: false,
                discard_response_by_lane: false,
                mark_response_ready: false,
                materialize_ready_items: false
            }
        }

        transition ResolveRealtimeAssistantTurnInterruptedValid {
            on input ResolveRealtimeAssistantTurnInterrupted { response_id_valid }
            guard {
                self.lifecycle_phase == Phase::Ready
                && response_id_valid
            }
            update {}
            to Ready
            emit RealtimeTranscriptEventResolved {
                observe_item: false,
                observe_skipped: false,
                write_user_segment: false,
                append_assistant_segment: false,
                replace_assistant_segment: false,
                promote_lane: false,
                mark_item_ready: false,
                record_delta_id: false,
                remove_completion: false,
                record_completion: true,
                discard_response: false,
                discard_response_by_lane: true,
                mark_response_ready: true,
                materialize_ready_items: true
            }
        }

        transition ResolveRealtimeMaterializeAlreadyDone {
            on input ResolveRealtimeMaterializeCandidate {
                item_materialized,
                predecessor_materialized,
                item_skipped,
                item_ready,
                item_text_present,
                role,
                response_id_present,
                completion_present,
                completion_usage_consumed
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && item_materialized
            }
            update {}
            to Ready
            emit RealtimeMaterializeCandidateResolved {
                decision: RealtimeTranscriptMaterializeDecision::Wait,
                consume_usage: false
            }
        }

        transition ResolveRealtimeMaterializeWaitForPredecessor {
            on input ResolveRealtimeMaterializeCandidate {
                item_materialized,
                predecessor_materialized,
                item_skipped,
                item_ready,
                item_text_present,
                role,
                response_id_present,
                completion_present,
                completion_usage_consumed
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && item_materialized == false
                && predecessor_materialized == false
            }
            update {}
            to Ready
            emit RealtimeMaterializeCandidateResolved {
                decision: RealtimeTranscriptMaterializeDecision::Wait,
                consume_usage: false
            }
        }

        transition ResolveRealtimeMaterializeSkipped {
            on input ResolveRealtimeMaterializeCandidate {
                item_materialized,
                predecessor_materialized,
                item_skipped,
                item_ready,
                item_text_present,
                role,
                response_id_present,
                completion_present,
                completion_usage_consumed
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && item_materialized == false
                && predecessor_materialized
                && item_skipped
            }
            update {}
            to Ready
            emit RealtimeMaterializeCandidateResolved {
                decision: RealtimeTranscriptMaterializeDecision::MarkSkipped,
                consume_usage: false
            }
        }

        transition ResolveRealtimeMaterializeWaitForReadyText {
            on input ResolveRealtimeMaterializeCandidate {
                item_materialized,
                predecessor_materialized,
                item_skipped,
                item_ready,
                item_text_present,
                role,
                response_id_present,
                completion_present,
                completion_usage_consumed
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && item_materialized == false
                && predecessor_materialized
                && item_skipped == false
                && (item_ready == false || item_text_present == false)
            }
            update {}
            to Ready
            emit RealtimeMaterializeCandidateResolved {
                decision: RealtimeTranscriptMaterializeDecision::Wait,
                consume_usage: false
            }
        }

        transition ResolveRealtimeMaterializeUser {
            on input ResolveRealtimeMaterializeCandidate {
                item_materialized,
                predecessor_materialized,
                item_skipped,
                item_ready,
                item_text_present,
                role,
                response_id_present,
                completion_present,
                completion_usage_consumed
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && item_materialized == false
                && predecessor_materialized
                && item_skipped == false
                && item_ready
                && item_text_present
                && role == RealtimeTranscriptRoleKind::User
            }
            update {}
            to Ready
            emit RealtimeMaterializeCandidateResolved {
                decision: RealtimeTranscriptMaterializeDecision::MaterializeUser,
                consume_usage: false
            }
        }

        transition ResolveRealtimeMaterializeAssistant {
            on input ResolveRealtimeMaterializeCandidate {
                item_materialized,
                predecessor_materialized,
                item_skipped,
                item_ready,
                item_text_present,
                role,
                response_id_present,
                completion_present,
                completion_usage_consumed
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && item_materialized == false
                && predecessor_materialized
                && item_skipped == false
                && item_ready
                && item_text_present
                && role == RealtimeTranscriptRoleKind::Assistant
                && response_id_present
                && completion_present
            }
            update {}
            to Ready
            emit RealtimeMaterializeCandidateResolved {
                decision: RealtimeTranscriptMaterializeDecision::MaterializeAssistant,
                consume_usage: completion_usage_consumed == false
            }
        }

        transition ResolveRealtimeMaterializeAssistantMissingCompletion {
            on input ResolveRealtimeMaterializeCandidate {
                item_materialized,
                predecessor_materialized,
                item_skipped,
                item_ready,
                item_text_present,
                role,
                response_id_present,
                completion_present,
                completion_usage_consumed
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && item_materialized == false
                && predecessor_materialized
                && item_skipped == false
                && item_ready
                && item_text_present
                && role == RealtimeTranscriptRoleKind::Assistant
                && (response_id_present == false || completion_present == false)
            }
            update {}
            to Ready
            emit RealtimeMaterializeCandidateResolved {
                decision: RealtimeTranscriptMaterializeDecision::Wait,
                consume_usage: false
            }
        }

        transition AuthorizeRestoreRealtimeTranscriptState {
            on input RestoreRealtimeTranscriptState {
                item_count,
                first_seen_count,
                first_seen_unique_count,
                every_item_has_order_entry,
                every_order_entry_has_item,
                all_identity_fields_valid,
                all_delta_ids_valid,
                all_completion_response_ids_valid,
                all_discarded_response_ids_valid,
                all_materialized_items_were_ready_or_skipped,
                all_assistant_items_have_response_unless_skipped,
                all_ready_assistant_items_have_completion_or_are_skipped,
                all_materialized_assistant_completions_consumed,
                all_completed_assistant_text_items_are_ready_or_materialized_or_skipped,
                all_discarded_assistant_items_are_skipped_or_materialized
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && item_count == first_seen_count
                && first_seen_count == first_seen_unique_count
                && every_item_has_order_entry
                && every_order_entry_has_item
                && all_identity_fields_valid
                && all_delta_ids_valid
                && all_completion_response_ids_valid
                && all_discarded_response_ids_valid
                && all_materialized_items_were_ready_or_skipped
                && all_assistant_items_have_response_unless_skipped
                && all_ready_assistant_items_have_completion_or_are_skipped
                && all_materialized_assistant_completions_consumed
                && all_completed_assistant_text_items_are_ready_or_materialized_or_skipped
                && all_discarded_assistant_items_are_skipped_or_materialized
            }
            update {}
            to Ready
            emit RealtimeTranscriptSnapshotRestoreAuthorized
        }

        // ===============================================================
        // Durable-config region (folded from the retired
        // SessionDurableConfigAuthorityMachine). Each transition reads only
        // the typed RAW observations carried on the input and resolves the
        // admission verdict. A request that fails the guard matches no
        // transition and surfaces to the shell as `Err` — exactly the
        // reject path the retired machine returned. The shell wrapper mirrors
        // the verdict (admit -> return the original typed value; reject ->
        // propagate the error) and decides nothing.
        // ===============================================================

        // ---------------------------------------------------------------
        // AuthorizeSessionMetadataPersist — admit a session-metadata persist
        // iff the record is well-formed enough to drive a session: a nonzero
        // schema version and a configured model. Ported verbatim from the
        // retired guard `schema_version > 0 && model_present`.
        // ---------------------------------------------------------------
        transition AuthorizeSessionMetadataPersist {
            on input AuthorizeSessionMetadataPersist {
                schema_version,
                model_present,
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && schema_version > 0
                && model_present == true
            }
            update {}
            to Ready
            emit SessionMetadataPersistAuthorized
        }

        // ---------------------------------------------------------------
        // AuthorizeSessionBuildStatePersist — admit a build-state persist iff
        // its mob-tool authority context is absent or is the generated
        // authority kind. Ported verbatim from the retired guard
        // `mob_tool_authority_context_present == false
        //  || mob_tool_authority_context_generated == true`.
        // ---------------------------------------------------------------
        transition AuthorizeSessionBuildStatePersist {
            on input AuthorizeSessionBuildStatePersist {
                mob_tool_authority_context_present,
                mob_tool_authority_context_generated,
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && (
                    mob_tool_authority_context_present == false
                    || mob_tool_authority_context_generated == true
                )
            }
            update {}
            to Ready
            emit SessionBuildStatePersistAuthorized
        }

        // ---------------------------------------------------------------
        // RestoreSessionBuildState — the recovery half of the build-state
        // fact. Ported verbatim from the retired guard, which authorized any
        // persisted build-state snapshot (`Ready`-only guard).
        // ---------------------------------------------------------------
        transition RestoreSessionBuildState {
            on input RestoreSessionBuildState
            guard { self.lifecycle_phase == Phase::Ready }
            update {}
            to Ready
            emit SessionBuildStateRestoreAuthorized
        }

        // ---------------------------------------------------------------
        // AuthorizeSystemPromptMutation — admit a system-prompt mutation iff
        // the prompt has content or is an explicit clear (zero bytes). Ported
        // verbatim from the retired guard
        // `prompt_present == true || prompt_byte_count == 0`.
        // ---------------------------------------------------------------
        transition AuthorizeSystemPromptMutation {
            on input AuthorizeSystemPromptMutation {
                source,
                prompt_present,
                prompt_byte_count,
                replacing_existing,
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && (prompt_present == true || prompt_byte_count == 0)
            }
            update {}
            to Ready
            emit SystemPromptMutationAuthorized
        }

        // ===============================================================
        // Pending-continuation region (folded from the retired
        // PendingContinuationAdmissionMachine). Both transitions read only the
        // typed RAW observations carried on the input and resolve the
        // disposition via `has_effective_pending_boundary`. The shell mirrors
        // the emitted disposition (and the public terminal witness) onto its
        // run-pending / start-turn-disposition path and decides nothing.
        // ===============================================================

        transition ResolvePendingContinuationWithBoundary {
            on input ResolvePendingContinuation {
                session_tail,
                staged_tool_result_count
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && has_effective_pending_boundary(session_tail, staged_tool_result_count)
            }
            update {}
            to Ready
            emit PendingContinuationResolved {
                disposition: PendingContinuationDisposition::RunPending
            }
        }

        transition ResolvePendingContinuationWithoutBoundary {
            on input ResolvePendingContinuation {
                session_tail,
                staged_tool_result_count
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && has_effective_pending_boundary(session_tail, staged_tool_result_count) == false
            }
            update {}
            to Ready
            emit PendingContinuationResolved {
                disposition: PendingContinuationDisposition::NoPendingBoundary
            }
            emit PendingContinuationPublicTerminalResolved {
                terminal: PendingContinuationPublicTerminal::NoPendingBoundary
            }
        }

        // ===============================================================
        // Resume-override-admission region. Reject transitions are guarded in
        // the shell's first-match-wins precedence order: each lower-priority
        // reject only fires when every higher-priority reject condition is
        // false. The three accept transitions split on the provider selection.
        // ===============================================================

        // Reject (priority 1): provider override without a model override.
        transition AuthorizeSessionResumeOverridesRejectProviderRequiresModel {
            on input AuthorizeSessionResumeOverrides {
                provider_override_present,
                model_override_present,
                has_build_only_overrides,
                first_turn_phase
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && resume_reject_provider_requires_model(
                    provider_override_present,
                    model_override_present
                )
            }
            update {}
            to Ready
            emit SessionResumeOverridesRejected {
                reason: ResumeOverrideRejection::ProviderRequiresModel
            }
        }

        // Reject (priority 2): build-only overrides after the first turn started.
        transition AuthorizeSessionResumeOverridesRejectBuildOnlyAfterFirstTurn {
            on input AuthorizeSessionResumeOverrides {
                provider_override_present,
                model_override_present,
                has_build_only_overrides,
                first_turn_phase
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && resume_reject_provider_requires_model(
                    provider_override_present,
                    model_override_present
                ) == false
                && resume_reject_build_only_after_first_turn(
                    has_build_only_overrides,
                    first_turn_phase
                )
            }
            update {}
            to Ready
            emit SessionResumeOverridesRejected {
                reason: ResumeOverrideRejection::BuildOnlyAfterFirstTurn
            }
        }

        // Accept (provider recomputed from a model-only change): clears stored
        // provider + self-hosted binding; provider_overridden is true.
        transition AuthorizeSessionResumeOverridesAcceptRecomputeProvider {
            on input AuthorizeSessionResumeOverrides {
                provider_override_present,
                model_override_present,
                has_build_only_overrides,
                first_turn_phase
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && resume_overrides_admissible(
                    provider_override_present,
                    model_override_present,
                    has_build_only_overrides,
                    first_turn_phase
                )
                && resume_provider_recompute_from_model(
                    model_override_present,
                    provider_override_present
                )
            }
            update {}
            to Ready
            emit SessionResumeOverridesAuthorized {
                provider_selection: ResumeProviderSelection::RecomputeFromModel,
                self_hosted_selection: ResumeSelfHostedSelection::Clear,
                provider_overridden: true
            }
        }

        // Accept (explicit provider override): use the override; self-hosted is
        // cleared because a provider override always rides a model override;
        // provider_overridden is true.
        transition AuthorizeSessionResumeOverridesAcceptUseOverride {
            on input AuthorizeSessionResumeOverrides {
                provider_override_present,
                model_override_present,
                has_build_only_overrides,
                first_turn_phase
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && resume_overrides_admissible(
                    provider_override_present,
                    model_override_present,
                    has_build_only_overrides,
                    first_turn_phase
                )
                && resume_provider_recompute_from_model(
                    model_override_present,
                    provider_override_present
                ) == false
                && provider_override_present
            }
            update {}
            to Ready
            emit SessionResumeOverridesAuthorized {
                provider_selection: ResumeProviderSelection::UseOverride,
                self_hosted_selection: ResumeSelfHostedSelection::Clear,
                provider_overridden: true
            }
        }

        // Accept (retain stored provider): no provider override and not a
        // model-only recompute. self-hosted retained iff the model is unchanged;
        // provider_overridden iff the model changed.
        transition AuthorizeSessionResumeOverridesAcceptRetainStored {
            on input AuthorizeSessionResumeOverrides {
                provider_override_present,
                model_override_present,
                has_build_only_overrides,
                first_turn_phase
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && resume_overrides_admissible(
                    provider_override_present,
                    model_override_present,
                    has_build_only_overrides,
                    first_turn_phase
                )
                && resume_provider_recompute_from_model(
                    model_override_present,
                    provider_override_present
                ) == false
                && provider_override_present == false
            }
            update {}
            to Ready
            emit SessionResumeOverridesAuthorized {
                provider_selection: ResumeProviderSelection::UseStored,
                self_hosted_selection: ResumeSelfHostedSelection::Retain,
                provider_overridden: false
            }
        }

        // ---------------------------------------------------------------
        // ClassifyLiveSessionAuthority — live-vs-durable session-document
        // authority reconciliation. The session-store shell extracts four pure
        // boolean divergence observations; THIS machine owns the verdict, the
        // precedence (archived > uncommitted transcript > runtime system-context
        // > stored transcript-revision), and the typed reason.
        //
        //   all four false                       -> LiveAuthoritative
        //   stored_is_archived                   -> Durable / StoredArchived
        //   live_has_uncommitted_transcript      -> Durable / LiveUncommittedTranscript
        //   runtime_system_context_diverged      -> Durable / RuntimeSystemContextDiverged
        //   else (stored_transcript_diverged)    -> Durable / StoredTranscriptRevisionDiverged
        //
        // The four Durable guards are mutually exclusive and, with the Live
        // guard, total over the boolean cube. Stateless self-loop in Ready.
        // ---------------------------------------------------------------
        transition ClassifyLiveSessionAuthorityLive {
            on input ClassifyLiveSessionAuthority {
                stored_transcript_diverged,
                live_has_uncommitted_transcript,
                runtime_system_context_diverged,
                stored_is_archived
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && stored_transcript_diverged == false
                && live_has_uncommitted_transcript == false
                && runtime_system_context_diverged == false
                && stored_is_archived == false
            }
            update {}
            to Ready
            emit LiveSessionAuthorityClassified {
                authority: LiveSessionAuthorityKind::LiveAuthoritative,
                reason: LiveSessionAuthorityReason::StoredArchived
            }
        }

        transition ClassifyLiveSessionAuthorityDurableArchived {
            on input ClassifyLiveSessionAuthority {
                stored_transcript_diverged,
                live_has_uncommitted_transcript,
                runtime_system_context_diverged,
                stored_is_archived
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && stored_is_archived == true
            }
            update {}
            to Ready
            emit LiveSessionAuthorityClassified {
                authority: LiveSessionAuthorityKind::DurableAuthoritative,
                reason: LiveSessionAuthorityReason::StoredArchived
            }
        }

        transition ClassifyLiveSessionAuthorityDurableUncommitted {
            on input ClassifyLiveSessionAuthority {
                stored_transcript_diverged,
                live_has_uncommitted_transcript,
                runtime_system_context_diverged,
                stored_is_archived
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && stored_is_archived == false
                && live_has_uncommitted_transcript == true
            }
            update {}
            to Ready
            emit LiveSessionAuthorityClassified {
                authority: LiveSessionAuthorityKind::DurableAuthoritative,
                reason: LiveSessionAuthorityReason::LiveUncommittedTranscript
            }
        }

        transition ClassifyLiveSessionAuthorityDurableSystemContext {
            on input ClassifyLiveSessionAuthority {
                stored_transcript_diverged,
                live_has_uncommitted_transcript,
                runtime_system_context_diverged,
                stored_is_archived
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && stored_is_archived == false
                && live_has_uncommitted_transcript == false
                && runtime_system_context_diverged == true
            }
            update {}
            to Ready
            emit LiveSessionAuthorityClassified {
                authority: LiveSessionAuthorityKind::DurableAuthoritative,
                reason: LiveSessionAuthorityReason::RuntimeSystemContextDiverged
            }
        }

        transition ClassifyLiveSessionAuthorityDurableRevision {
            on input ClassifyLiveSessionAuthority {
                stored_transcript_diverged,
                live_has_uncommitted_transcript,
                runtime_system_context_diverged,
                stored_is_archived
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && stored_is_archived == false
                && live_has_uncommitted_transcript == false
                && runtime_system_context_diverged == false
                && stored_transcript_diverged == true
            }
            update {}
            to Ready
            emit LiveSessionAuthorityClassified {
                authority: LiveSessionAuthorityKind::DurableAuthoritative,
                reason: LiveSessionAuthorityReason::StoredTranscriptRevisionDiverged
            }
        }

        // ===============================================================
        // Recovery-source-projection region (KEYSTONE). Both transitions read
        // typed store/runtime observations and resolve the recoverable
        // verdict via `store_projection_can_recover_authority`. The verdict is
        // total over the boolean cube, so it is emitted on both branches; the
        // shell mirrors `recoverable` onto its load fallback and decides
        // nothing. Fails closed.
        // ===============================================================

        transition RecoverSessionFromStoreAuthorized {
            on input RecoverSessionFromStore {
                session_id,
                has_metadata,
                has_build_state,
                runtime_projection_quarantined
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && store_projection_can_recover_authority(
                    has_metadata,
                    has_build_state,
                    runtime_projection_quarantined
                )
            }
            update {}
            to Ready
            emit SessionStoreRecoverySourceResolved { recoverable: true }
        }

        transition RecoverSessionFromStoreUnrecoverable {
            on input RecoverSessionFromStore {
                session_id,
                has_metadata,
                has_build_state,
                runtime_projection_quarantined
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && store_projection_can_recover_authority(
                    has_metadata,
                    has_build_state,
                    runtime_projection_quarantined
                ) == false
            }
            update {}
            to Ready
            emit SessionStoreRecoverySourceResolved { recoverable: false }
        }

        // ===============================================================
        // Runtime-projection-rollback region. Both transitions read the pure
        // continuation observation and resolve the disposition of a
        // runtime-authoritative projection save whose durable row ran ahead
        // of the authority transcript. Total over the observation: a row
        // that faithfully continues the authority (its tail is turn content
        // whose boundary commit never landed) is rebuilt onto committed
        // truth; anything else keeps the fail-closed rejection. The shell
        // mirrors the disposition.
        // ===============================================================

        transition ResolveRuntimeProjectionRollbackRebuild {
            on input ResolveRuntimeProjectionRollback {
                session_id,
                row_continues_authority,
                row_is_runtime_checkpoint
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && row_continues_authority == true
                && row_is_runtime_checkpoint == true
            }
            update {}
            to Ready
            emit RuntimeProjectionRollbackResolved {
                disposition: RuntimeProjectionRollbackDisposition::RebuildToAuthority
            }
        }

        transition ResolveRuntimeProjectionRollbackReject {
            on input ResolveRuntimeProjectionRollback {
                session_id,
                row_continues_authority,
                row_is_runtime_checkpoint
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && (row_continues_authority == false
                    || row_is_runtime_checkpoint == false)
            }
            update {}
            to Ready
            emit RuntimeProjectionRollbackResolved {
                disposition: RuntimeProjectionRollbackDisposition::RejectDivergent
            }
        }

        // ===============================================================
        // Apply-pending-tool-results region. The transition reads the consumed
        // result count and authorizes the apply, emitting `applied_count` equal
        // to `result_count` (vacuous-accept, mirroring the staging-side
        // StageSessionToolResults shape). The shell mirrors `applied_count`
        // onto its `agent.apply_pending_tool_results` call and decides nothing.
        // ===============================================================

        transition ApplyPendingToolResults {
            on input ApplyPendingToolResults {
                session_id,
                result_count
            }
            guard { self.lifecycle_phase == Phase::Ready }
            update {}
            to Ready
            emit SessionToolResultsApplied {
                session_id: session_id,
                applied_count: result_count
            }
        }

        // ===============================================================
        // Transcript-edit region. Each transition reads the typed
        // `TranscriptEditKind` directive and authorizes the commit, echoing the
        // kind so the shell routes to the correct persist handler. The shell
        // mirrors `success` onto its persist path and decides nothing.
        // ===============================================================

        transition TranscriptEditFork {
            on input TranscriptEdit {
                session_id,
                fork_or_rewrite_directive
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && fork_or_rewrite_directive == TranscriptEditKind::Fork
            }
            update {}
            to Ready
            emit TranscriptRewriteCommitted {
                kind: TranscriptEditKind::Fork,
                success: true
            }
        }

        transition TranscriptEditRewrite {
            on input TranscriptEdit {
                session_id,
                fork_or_rewrite_directive
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && fork_or_rewrite_directive == TranscriptEditKind::Rewrite
            }
            update {}
            to Ready
            emit TranscriptRewriteCommitted {
                kind: TranscriptEditKind::Rewrite,
                success: true
            }
        }

        // ===============================================================
        // Lifecycle-terminal region (LUC-524 R004 fold). The recover
        // transition adopts the canonical current archived-ness into the
        // machine-owned registry; the two archive transitions decide the
        // disposition and the realization action vector from that
        // machine-owned terminal state. The Archive guards read the
        // machine's own map — a drive against an unseeded session id fails
        // closed at the generated accessor, so the shell MUST recover-seed
        // before driving the archive input.
        // ===============================================================

        transition RecoverSessionLifecycleTerminal {
            on input RecoverSessionLifecycleTerminal { session_id, terminal }
            guard {
                self.lifecycle_phase == Phase::Ready
                && (terminal == SessionDocumentLifecycle::Active
                    || terminal == SessionDocumentLifecycle::Archived)
            }
            update {
                self.session_lifecycle_terminal.insert(session_id, terminal);
            }
            to Ready
            emit SessionLifecycleTerminalRecovered
        }

        // Archive from Active: the only transition that moves the document
        // lifecycle to Archived. The action vector instructs the shell to
        // commit the durable document iff a durable snapshot exists, and to
        // retire the runtime iff the archive is runtime-backed and the
        // runtime actually knows the session.
        transition ArchiveSessionDocumentActive {
            on input ArchiveSessionDocument {
                session_id,
                runtime_backed,
                durable_snapshot_present,
                runtime_session_registered
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && self.session_lifecycle_terminal.get_cloned(session_id).get("value")
                    == SessionDocumentLifecycle::Active
            }
            update {
                self.session_lifecycle_terminal
                    .insert(session_id, SessionDocumentLifecycle::Archived);
            }
            to Ready
            emit SessionArchiveResolved {
                disposition: SessionArchiveDisposition::Archive,
                write_document: durable_snapshot_present,
                retire_runtime: archive_should_retire_runtime(
                    runtime_backed,
                    durable_snapshot_present,
                    runtime_session_registered)
            }
        }

        // Idempotent re-archive: an already-Archived document resolves to an
        // explicit AlreadyArchived verdict with an empty action vector. The
        // surface contract maps this verdict to its existing NotFound error.
        transition ArchiveSessionDocumentAlreadyArchived {
            on input ArchiveSessionDocument {
                session_id,
                runtime_backed,
                durable_snapshot_present,
                runtime_session_registered
            }
            guard {
                self.lifecycle_phase == Phase::Ready
                && self.session_lifecycle_terminal.get_cloned(session_id).get("value")
                    == SessionDocumentLifecycle::Archived
            }
            update {}
            to Ready
            emit SessionArchiveResolved {
                disposition: SessionArchiveDisposition::AlreadyArchived,
                write_document: false,
                retire_runtime: false
            }
        }

    }
}