brokk-mj-core 2.6.2

Session control plane for ACP coding agents
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
//! The deterministic relay state machine: commands, events, observations,
//! and the snapshot they fold into. `apply_relay_event` is the single place
//! that turns one more event into the next snapshot; everything else here is
//! either a type that shape describes, or the byte-budget/truncation and
//! digest machinery that keeps events and snapshots bounded and verifiable.
//! Nothing in this module touches the filesystem.

use std::collections::BTreeMap;

use agent_client_protocol::schema::ProtocolVersion as AcpProtocolVersion;
use agent_client_protocol::schema::v1::{
    AgentCapabilities, AvailableCommand, ContentBlock, Implementation, SessionConfigOption,
    SessionModeState, SessionUpdate,
};
use anyhow::{Context, Result, anyhow, bail};
use serde::{Deserialize, Serialize};

use crate::hel_config::HarnessKind;
use crate::hel_elicitation::ElicitationRequest;
use serde_json::Value;
use sha2::{Digest, Sha256};

use super::capacity::{CAPACITY_STOP_REASON, CapacityRetry};

use super::{
    RELAY_EVENT_DIGEST_DOMAIN, RELAY_EVENT_DIGEST_DOMAIN_V2, RELAY_EVENT_GENESIS_DIGEST,
    RELAY_STATE_VERSION, RELAY_TRUNCATION_FLOOR,
};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
    tag = "type",
    content = "data",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum RelayCommand {
    Prompt {
        prompt: Vec<ContentBlock>,
    },
    RunUserShell {
        command: String,
    },
    CancelUserShell {
        shell_command_id: String,
    },
    RemoveQueuedPrompt {
        queued_command_id: String,
    },
    ClearQueuedPrompts,
    SetConfig {
        key: String,
        value: String,
    },
    /// Opaque ACP `session/set_mode` id. Hel uses it for harnesses whose plan
    /// mode is a session mode rather than an advertised slash command.
    SetSessionMode {
        mode_id: String,
    },
    /// Cancel the current turn without consuming a queued prompt. This is
    /// separate from [`RelayCommand::Cancel`], whose UI semantics may steer
    /// the next queued prompt into the running turn.
    CancelTurn,
    Cancel,
    Close {
        barrier_command_id: String,
        expected: RelayCursor,
    },
    BeginCheckpoint {
        reason: Option<String>,
    },
    CompleteCheckpoint {
        barrier_command_id: String,
    },
    /// Resume ACP dispatch for a barrier whose archive is exported but not yet
    /// installed on the controller. The recovery floor deliberately stays put:
    /// only [`RelayCommand::AdvanceRecoveryFloor`] may release journal history,
    /// and only once an archive covering that history is durably installed.
    ReleaseCheckpoint {
        barrier_command_id: String,
    },
    /// Move the recovery floor to a cursor that an installed archive covers.
    /// Valid with or without an active barrier.
    AdvanceRecoveryFloor {
        through: RelayCursor,
    },
    /// Put a controller-authored line into the conversation. The agent never
    /// sees it: it explains something Hel did to the session, such as moving
    /// its checkout, to the person reading the transcript.
    RecordNotice {
        text: String,
    },
}

impl RelayCommand {
    pub fn minimum_protocol(&self) -> u32 {
        match self {
            Self::RunUserShell { .. } | Self::CancelUserShell { .. } => 5,
            Self::CancelTurn => 7,
            Self::Prompt { prompt } if crate::hel_attachment::has_references(prompt) => 8,
            _ => super::RELAY_MIN_PROTOCOL_VERSION,
        }
    }

    /// Whether this command waits its turn in the durable command queue.
    pub(crate) fn is_queue_entry(&self) -> bool {
        matches!(self, Self::Prompt { .. } | Self::SetConfig { .. })
    }

    pub(crate) fn is_relay_local(&self) -> bool {
        matches!(
            self,
            Self::RemoveQueuedPrompt { .. }
                | Self::ClearQueuedPrompts
                | Self::CompleteCheckpoint { .. }
                | Self::ReleaseCheckpoint { .. }
                | Self::AdvanceRecoveryFloor { .. }
                | Self::RecordNotice { .. }
        )
    }

    pub(crate) fn is_effectful_acp(&self) -> bool {
        matches!(
            self,
            Self::Prompt { .. }
                | Self::SetConfig { .. }
                | Self::SetSessionMode { .. }
                | Self::CancelTurn
                | Self::Cancel
                | Self::Close { .. }
        )
    }

    pub(crate) fn is_effectful_user_shell(&self) -> bool {
        matches!(
            self,
            Self::RunUserShell { .. } | Self::CancelUserShell { .. }
        )
    }

    pub const fn kind(&self) -> RelayCommandKind {
        match self {
            Self::Prompt { .. } => RelayCommandKind::Prompt,
            Self::RunUserShell { .. } => RelayCommandKind::RunUserShell,
            Self::CancelUserShell { .. } => RelayCommandKind::CancelUserShell,
            Self::RemoveQueuedPrompt { .. } => RelayCommandKind::RemoveQueuedPrompt,
            Self::ClearQueuedPrompts => RelayCommandKind::ClearQueuedPrompts,
            Self::SetConfig { .. } => RelayCommandKind::SetConfig,
            Self::SetSessionMode { .. } => RelayCommandKind::SetSessionMode,
            Self::CancelTurn => RelayCommandKind::CancelTurn,
            Self::Cancel => RelayCommandKind::Cancel,
            Self::Close { .. } => RelayCommandKind::Close,
            Self::BeginCheckpoint { .. } => RelayCommandKind::BeginCheckpoint,
            Self::CompleteCheckpoint { .. } => RelayCommandKind::CompleteCheckpoint,
            Self::ReleaseCheckpoint { .. } => RelayCommandKind::ReleaseCheckpoint,
            Self::AdvanceRecoveryFloor { .. } => RelayCommandKind::AdvanceRecoveryFloor,
            Self::RecordNotice { .. } => RelayCommandKind::RecordNotice,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RelayCommandKind {
    Prompt,
    RunUserShell,
    CancelUserShell,
    RemoveQueuedPrompt,
    ClearQueuedPrompts,
    SetConfig,
    SetSessionMode,
    CancelTurn,
    Cancel,
    Close,
    BeginCheckpoint,
    CompleteCheckpoint,
    ReleaseCheckpoint,
    AdvanceRecoveryFloor,
    RecordNotice,
}

/// Payload-free queue identity exposed in attach/status responses.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QueuedRelayPrompt {
    pub command_id: String,
    pub created_at_ms: i64,
}

/// Payload-free active prompt identity exposed in attach/status responses.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActiveRelayPrompt {
    pub command_id: String,
    pub created_at_ms: i64,
    pub started_at_ms: i64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActiveUserShell {
    pub command_id: String,
    pub command: String,
    pub created_at_ms: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_at_ms: Option<i64>,
}

/// A terminal the ACP agent asked Hel to run on its behalf.
///
/// Unlike a transcript tool call, this is live operational state: it exists
/// only while the child process is alive and lets clients show truthful
/// activity when an agent fails to publish the matching ACP tool update.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActiveAgentTerminal {
    pub terminal_id: String,
    pub command: String,
    pub started_at_ms: i64,
}

/// A command the agent left running with nothing waiting on it.
///
/// Harnesses produce these differently: Hel-hosted terminals that outlive
/// their tool card, provider-owned task levels, and Codex exec cards whose
/// result carries no exit code. The relay reduces them to this one shape so
/// every surface renders them the same way.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BackgroundCommand {
    /// Process-local identity. Clients must treat this as opaque and return it
    /// unchanged when requesting a stop.
    #[serde(default)]
    pub id: String,
    pub started_at_ms: i64,
    pub command: String,
    /// Whether the current worker can stop this task without ending its turn.
    #[serde(default)]
    pub can_stop: bool,
}

/// The process owner behind one stoppable background-command id.
///
/// This never crosses the relay wire. The worker resolves the opaque public id
/// against its current live state before handing the target to the ACP bridge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BackgroundTaskStopTarget {
    HostedTerminal { terminal_id: String },
    ClaudeAsyncTask { task_id: String },
}

/// A turn the harness started on its own, with no prompt in flight.
///
/// Claude Code re-invokes itself when a background task it started finishes.
/// The adapter streams that work through ordinary `session/update`
/// notifications and settles it with a `usage_update` carrying an origin
/// marker, so the relay models it as a turn rather than as idle chatter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct HarnessTurn {
    pub started_at_ms: i64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UserShellStatus {
    Exited,
    Signaled,
    TimedOut,
    Cancelled,
    Interrupted,
    Failed,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UserShellResult {
    pub command: String,
    pub stdout: String,
    pub stderr: String,
    #[serde(default)]
    pub stdout_truncated: bool,
    #[serde(default)]
    pub stderr_truncated: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signal: Option<String>,
    pub duration_ms: u64,
    pub status: UserShellStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

impl UserShellResult {
    pub fn prompt_context(&self) -> String {
        fn escaped(text: &str) -> String {
            text.replace('&', "&amp;")
                .replace('<', "&lt;")
                .replace('>', "&gt;")
        }

        let status = match self.status {
            UserShellStatus::Exited => "exited",
            UserShellStatus::Signaled => "signaled",
            UserShellStatus::TimedOut => "timed_out",
            UserShellStatus::Cancelled => "cancelled",
            UserShellStatus::Interrupted => "interrupted",
            UserShellStatus::Failed => "failed",
        };
        let mut result = format!("status: {status}\nduration_ms: {}", self.duration_ms);
        if let Some(exit_code) = self.exit_code {
            result.push_str(&format!("\nexit_code: {exit_code}"));
        }
        if let Some(signal) = &self.signal {
            result.push_str(&format!("\nsignal: {}", escaped(signal)));
        }
        if let Some(error) = &self.error {
            result.push_str(&format!("\nerror: {}", escaped(error)));
        }
        if !self.stdout.is_empty() {
            result.push_str(&format!("\nstdout:\n{}", escaped(&self.stdout)));
        }
        if !self.stderr.is_empty() {
            result.push_str(&format!("\nstderr:\n{}", escaped(&self.stderr)));
        }
        format!(
            "<user_shell_command>\n<command>{}</command>\n<result>{result}</result>\n</user_shell_command>",
            escaped(&self.command)
        )
    }
}

/// One entry of the durable command queue. Prompts and configuration changes
/// share the queue so they run in the order the user submitted them.
///
/// The payload is untagged so entries written before configuration changes
/// could be queued still load: they carry a `prompt` field and nothing else.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct StoredQueuedRelayCommand {
    pub(crate) command_id: String,
    #[serde(flatten)]
    pub(crate) payload: StoredQueuedRelayPayload,
    pub(crate) created_at_ms: i64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub(crate) enum StoredQueuedRelayPayload {
    Prompt { prompt: Vec<ContentBlock> },
    SetConfig { key: String, value: String },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct StoredActiveRelayPrompt {
    pub(crate) command_id: String,
    pub(crate) prompt: Vec<ContentBlock>,
    pub(crate) created_at_ms: i64,
    pub(crate) started_at_ms: i64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RelayExecutionState {
    Idle,
    Running,
    Closing,
    Closed,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RelayCursor {
    pub ordinal: u64,
    pub digest: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RelayOperationalState {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capacity_retry: Option<CapacityRetry>,
    pub session_id: String,
    /// Start of the latest turn, retained until its background work settles.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub activity_turn_started_at_ms: Option<i64>,
    /// Durable identity of this relay store, replaced by a fresh restore.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub store_id: Option<String>,
    /// Start of the current observed idle period; older workers leave it unknown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub idle_since_ms: Option<i64>,
    pub execution: RelayExecutionState,
    pub latest_ordinal: u64,
    pub latest_digest: String,
    pub acknowledged_through: u64,
    pub acknowledged_digest: String,
    /// Highest verified checkpoint frontier. Events newer than this remain in
    /// the relay journal even after acknowledgement.
    pub recovery_floor_ordinal: u64,
    pub recovery_floor_digest: String,
    pub native_session_id: Option<String>,
    /// Whether the current worker process has finished opening its ACP
    /// session. Older workers omit this field and are treated as ready.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub acp_ready: Option<bool>,
    pub agent_capabilities: Option<Box<AgentCapabilities>>,
    pub agent_info: Option<Implementation>,
    /// Older workers do not report the optional ACP steering extension.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub steering_supported: Option<bool>,
    pub config_options: Vec<SessionConfigOption>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub modes: Option<SessionModeState>,
    pub available_commands: Vec<AvailableCommand>,
    pub config: BTreeMap<String, String>,
    pub active_prompt: Option<ActiveRelayPrompt>,
    pub queued_prompts: Vec<QueuedRelayPrompt>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub active_user_shells: Vec<ActiveUserShell>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub active_agent_terminals: Vec<ActiveAgentTerminal>,
    pub checkpoint_barrier: Option<String>,
    pub checkpoint_ready: Option<RelayCursor>,
    /// When anything at all last arrived over ACP. This is the liveness
    /// signal — a bridge that has gone quiet — not the step clock: a
    /// streaming message refreshes it many times a second.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_acp_activity_at_ms: Option<i64>,
    /// When the step the agent is on began, in epoch milliseconds, while a
    /// step is in flight. A worker too old to report it leaves this empty and
    /// the step clock falls back to the turn it belongs to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_step_started_at_ms: Option<i64>,
    /// When the newest tool call still reporting pending or in-progress
    /// started its current status. Unlike the general step clock, this is
    /// positive evidence of foreground work even when the harness exposes no
    /// turn boundary of its own.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub foreground_tool_started_at_ms: Option<i64>,
    /// The turn the harness started on its own, while it is open.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub harness_turn: Option<HarnessTurn>,
    /// Ordinal of the newest `harness_turn_started` event, whether or not that
    /// turn is still open. It only moves forward, so a checkpoint can compare
    /// it against the cursor it captured.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_harness_turn_started_ordinal: Option<u64>,
    /// Commands the agent left running while nothing waits on them, oldest
    /// first. Live operational state, like `active_agent_terminals`: it is
    /// derived from what the relay can see now, not from the journal.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub background_commands: Vec<BackgroundCommand>,
    /// Whether provider-owned background work is known for this worker
    /// process. Only Kimi needs this today; older workers and other harnesses
    /// omit it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background_work_known: Option<bool>,
}

impl RelayOperationalState {
    /// Whether this worker has a usable native ACP session.
    ///
    /// Workers predating `acp_ready` are treated as ready for compatibility;
    /// a current worker that explicitly reports not ready is authoritative.
    #[must_use]
    pub fn native_session_is_ready(&self) -> bool {
        self.execution != RelayExecutionState::Closed
            && self.native_session_id.is_some()
            && self.acp_ready.unwrap_or(true)
    }

    /// Whether nothing the worker owns would be destroyed by killing it now.
    ///
    /// Stopping a worker tears down the ACP bridge with it, so any operation
    /// that replaces a worker in place has to wait for this. Every way the
    /// session can still be holding work is listed here, and each is a
    /// separate fact: the agent can be mid-turn, the harness can have started
    /// a turn of its own, a foreground tool, a terminal or a command it
    /// launched can still be running, a prompt can be queued behind the
    /// current one, a user shell can be open, and a checkpoint barrier can be
    /// waiting to capture.
    #[must_use]
    pub fn is_quiet(&self) -> bool {
        self.execution == RelayExecutionState::Idle
            && self.acp_ready != Some(false)
            && self.background_work_known != Some(false)
            && self.active_prompt.is_none()
            && self.harness_turn.is_none()
            && self.queued_prompts.is_empty()
            && self.active_user_shells.is_empty()
            && self.active_agent_terminals.is_empty()
            && self.foreground_tool_started_at_ms.is_none()
            && self.background_commands.is_empty()
            && self.checkpoint_barrier.is_none()
    }

    /// Whether a controller may replace this worker without losing work.
    ///
    /// An older Kimi worker cannot report provider-owned background agents,
    /// so its otherwise-quiet snapshot is not proof that replacement is safe.
    #[must_use]
    pub fn safe_to_replace(&self, harness: HarnessKind) -> bool {
        self.is_quiet()
            && (harness != HarnessKind::Kimi || self.background_work_known == Some(true))
    }

    /// Whether a routine checkpoint may admit a barrier without risking work
    /// owned by a Kimi provider process. Older Kimi workers omit the
    /// synchronization field, so they must fail closed just like replacement
    /// does. Other harnesses retain their historical checkpoint behavior.
    #[must_use]
    pub fn safe_for_checkpoint(&self, harness: HarnessKind) -> bool {
        harness != HarnessKind::Kimi
            || (self.background_work_known == Some(true) && self.background_commands.is_empty())
    }
}

/// On-disk record format for a relay event.
/// - `1` (chained): folds `previous_digest` into the digest, forming a hash
///   chain. This is the legacy format; a record with no `format` key on disk is
///   read as v1.
/// - `2` (self-describing): carries no `previous_digest`; the digest depends
///   only on the record's own content, so a corrupt record cannot invalidate
///   its neighbours.
pub const RELAY_EVENT_FORMAT_V1: u8 = 1;
pub const RELAY_EVENT_FORMAT_V2: u8 = 2;

fn default_relay_event_format() -> u8 {
    RELAY_EVENT_FORMAT_V1
}

fn is_relay_event_format_v1(format: &u8) -> bool {
    *format == RELAY_EVENT_FORMAT_V1
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RelayEvent {
    /// Record format. Skipped on the wire when v1 so existing v1 journals
    /// round-trip byte-for-byte and old records (no `format` key) read as v1.
    #[serde(
        default = "default_relay_event_format",
        skip_serializing_if = "is_relay_event_format_v1"
    )]
    pub format: u8,
    pub ordinal: u64,
    /// Predecessor digest, forming the v1 chain. Absent (empty) for v2 records.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub previous_digest: String,
    pub digest: String,
    pub recorded_at_ms: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command_id: Option<String>,
    pub observation: RelayObservation,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RelayObservation {
    AgentInitialized {
        protocol_version: AcpProtocolVersion,
        capabilities: Box<AgentCapabilities>,
        agent_info: Option<Implementation>,
    },
    SessionOpened {
        native_session_id: String,
        resumed: bool,
    },
    SessionConfigured {
        config_options: Vec<SessionConfigOption>,
    },
    SessionModesConfigured {
        modes: Option<SessionModeState>,
    },
    SessionUpdate {
        update: Box<SessionUpdate>,
    },
    PermissionAutoApproved {
        option_id: String,
        option_name: String,
    },
    ElicitationRequested {
        request: ElicitationRequest,
    },
    ElicitationResolved {
        elicitation_id: String,
        action: String,
    },
    ElicitationsCleared,
    CommandQueued {
        command_id: String,
        command: RelayCommand,
        created_at_ms: i64,
    },
    CommandStarted {
        command_id: String,
        started_at_ms: i64,
    },
    CommandCompleted {
        command_id: String,
        outcome: RelayCommandOutcome,
    },
    CommandRejected {
        command_id: String,
        command: RelayCommandKind,
        message: String,
    },
    CommandInterrupted {
        command_id: String,
        command: RelayCommandKind,
        message: String,
    },
    UserShellOutput {
        command_id: String,
        command: String,
        stdout: String,
        stderr: String,
        stdout_truncated: bool,
        stderr_truncated: bool,
    },
    ConfigurationUpdated {
        key: String,
        value: String,
    },
    CheckpointReady {
        command_id: String,
        through: u64,
    },
    Warning {
        message: String,
    },
    /// The target-side session control plane was replaced. This is a typed
    /// transcript event so clients can surface it as unread attention without
    /// interpreting arbitrary system text.
    SessionRestarted,
    /// What a client-run terminal produced, journaled once when its child was
    /// reaped. The agent already read the full output over `terminal/output`;
    /// this copy is tail-capped for the person reading the transcript.
    TerminalOutput {
        terminal_id: String,
        output: String,
        truncated: bool,
        exit_code: Option<u32>,
        signal: Option<String>,
    },
    /// A controller-authored conversation line. Unlike a warning it reports
    /// something Hel did on purpose, so it reaches the transcript unadorned.
    Notice {
        message: String,
    },
    /// The harness began working with no prompt in flight. Recorded just
    /// before the agent output that revealed it, so the turn covers that
    /// output.
    HarnessTurnStarted {
        started_at_ms: i64,
    },
    /// The harness reached a turn boundary on its own. `origin` is the
    /// adapter's reported origin kind, kept for diagnostics.
    HarnessTurnSettled {
        origin: Option<String>,
        /// Whether a prompt of ours was still running when the turn settled.
        /// The relay keeps `Running` for it; the projection cannot see
        /// `active_prompt`, so the event carries the answer.
        #[serde(default)]
        prompt_in_flight: bool,
    },
    Closing,
    Closed,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RelayCommandOutcome {
    Prompt { stop_reason: String },
    UserShell { result: UserShellResult },
    UserShellCancelled,
    Configured,
    SessionModeSet,
    Cancelled,
    Steered { queued_command_id: String },
    Closed,
    QueueChanged { removed_command_ids: Vec<String> },
    CheckpointCompleted,
    CheckpointReleased,
    RecoveryFloorAdvanced,
    NoticeRecorded,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClaimedSteeringPrompt {
    /// Runtime-only store location; never sent or persisted.
    #[serde(skip)]
    pub attachment_root: Option<std::path::PathBuf>,
    pub queued_command_id: String,
    pub prompt: Vec<ContentBlock>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClaimedRelayCommand {
    pub command_id: String,
    pub accepted_ordinal: u64,
    pub command: RelayCommand,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hidden_prompt_context: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub steering_prompt: Option<ClaimedSteeringPrompt>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct PendingPromptContext {
    pub(crate) text: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) attached_command_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct PendingUserShellContext {
    pub(crate) shell_command_id: String,
    pub(crate) accepted_ordinal: u64,
    pub(crate) text: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) attached_command_id: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum RelayDispatchState {
    Queued,
    Pending,
    InFlight,
    Completed,
    Rejected,
    Interrupted,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct RelayDispatchRecord {
    pub(crate) command: RelayCommand,
    pub(crate) state: RelayDispatchState,
}

/// The durable half of an open harness-initiated turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct StoredHarnessTurn {
    pub(crate) started_at_ms: i64,
    /// Ordinal of the `harness_turn_started` event that opened this turn.
    pub(crate) first_ordinal: u64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct HandledRelayCommand {
    pub(crate) command: RelayCommand,
    pub(crate) accepted_ordinal: u64,
    pub(crate) terminal_ordinal: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct RelaySnapshot {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) capacity_retry: Option<CapacityRetry>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) activity_turn_started_at_ms: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) store_id: Option<String>,
    pub(crate) format_version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) idle_since_ms: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) activity_was_idle: Option<bool>,
    pub(crate) session_id: String,
    pub(crate) execution: RelayExecutionState,
    pub(crate) latest_ordinal: u64,
    pub(crate) latest_digest: String,
    pub(crate) acknowledged_through: u64,
    pub(crate) acknowledged_digest: String,
    pub(crate) recovery_floor_ordinal: u64,
    pub(crate) recovery_floor_digest: String,
    pub(crate) native_session_id: Option<String>,
    pub(crate) agent_capabilities: Option<Box<AgentCapabilities>>,
    pub(crate) agent_info: Option<Implementation>,
    pub(crate) config_options: Vec<SessionConfigOption>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) modes: Option<SessionModeState>,
    pub(crate) available_commands: Vec<AvailableCommand>,
    pub(crate) config: BTreeMap<String, String>,
    pub(crate) active_prompt: Option<StoredActiveRelayPrompt>,
    pub(crate) queued_prompts: Vec<StoredQueuedRelayCommand>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) pending_prompt_context: Option<PendingPromptContext>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) pending_user_shell_contexts: Vec<PendingUserShellContext>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub(crate) active_user_shells: BTreeMap<String, ActiveUserShell>,
    pub(crate) checkpoint_barrier: Option<String>,
    pub(crate) checkpoint_ready_through: Option<u64>,
    pub(crate) checkpoint_ready_digest: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) harness_turn: Option<StoredHarnessTurn>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) last_harness_turn_started_ordinal: Option<u64>,
    pub(crate) handled_commands: BTreeMap<String, HandledRelayCommand>,
    pub(crate) dispatches: BTreeMap<String, RelayDispatchRecord>,
}

impl RelaySnapshot {
    pub(crate) fn new(session_id: String) -> Self {
        Self {
            capacity_retry: None,
            activity_turn_started_at_ms: None,
            store_id: None,
            format_version: RELAY_STATE_VERSION,
            idle_since_ms: None,
            activity_was_idle: None,
            session_id,
            execution: RelayExecutionState::Idle,
            latest_ordinal: 0,
            latest_digest: RELAY_EVENT_GENESIS_DIGEST.to_owned(),
            acknowledged_through: 0,
            acknowledged_digest: RELAY_EVENT_GENESIS_DIGEST.to_owned(),
            recovery_floor_ordinal: 0,
            recovery_floor_digest: RELAY_EVENT_GENESIS_DIGEST.to_owned(),
            native_session_id: None,
            agent_capabilities: None,
            agent_info: None,
            config_options: Vec::new(),
            modes: None,
            available_commands: Vec::new(),
            config: BTreeMap::new(),
            active_prompt: None,
            queued_prompts: Vec::new(),
            pending_prompt_context: None,
            pending_user_shell_contexts: Vec::new(),
            active_user_shells: BTreeMap::new(),
            checkpoint_barrier: None,
            checkpoint_ready_through: None,
            checkpoint_ready_digest: None,
            harness_turn: None,
            last_harness_turn_started_ordinal: None,
            handled_commands: BTreeMap::new(),
            dispatches: BTreeMap::new(),
        }
    }

    pub(crate) fn operational_state(&self) -> RelayOperationalState {
        RelayOperationalState {
            capacity_retry: self.capacity_retry.clone().filter(|r| !r.submitted),
            activity_turn_started_at_ms: self.activity_turn_started_at_ms,
            store_id: self.store_id.clone(),
            session_id: self.session_id.clone(),
            idle_since_ms: self.idle_since_ms,
            execution: self.execution,
            latest_ordinal: self.latest_ordinal,
            latest_digest: self.latest_digest.clone(),
            acknowledged_through: self.acknowledged_through,
            acknowledged_digest: self.acknowledged_digest.clone(),
            recovery_floor_ordinal: self.recovery_floor_ordinal,
            recovery_floor_digest: self.recovery_floor_digest.clone(),
            native_session_id: self.native_session_id.clone(),
            // Readiness belongs to the current worker process, so durable
            // snapshots must never carry it across a restart.
            acp_ready: None,
            agent_capabilities: self.agent_capabilities.clone(),
            agent_info: self.agent_info.clone(),
            // Steering support belongs to the connected harness, like readiness.
            steering_supported: None,
            config_options: self.config_options.clone(),
            modes: self.modes.clone(),
            available_commands: self.available_commands.clone(),
            config: self.config.clone(),
            active_prompt: self.active_prompt.as_ref().map(|prompt| ActiveRelayPrompt {
                command_id: prompt.command_id.clone(),
                created_at_ms: prompt.created_at_ms,
                started_at_ms: prompt.started_at_ms,
            }),
            queued_prompts: self
                .queued_prompts
                .iter()
                .map(|prompt| QueuedRelayPrompt {
                    command_id: prompt.command_id.clone(),
                    created_at_ms: prompt.created_at_ms,
                })
                .collect(),
            active_user_shells: self.active_user_shells.values().cloned().collect(),
            active_agent_terminals: Vec::new(),
            checkpoint_barrier: self.checkpoint_barrier.clone(),
            checkpoint_ready: self
                .checkpoint_ready_through
                .zip(self.checkpoint_ready_digest.as_ref())
                .map(|(ordinal, digest)| RelayCursor {
                    ordinal,
                    digest: digest.clone(),
                }),
            last_acp_activity_at_ms: None,
            current_step_started_at_ms: None,
            foreground_tool_started_at_ms: None,
            harness_turn: self.harness_turn.map(|turn| HarnessTurn {
                started_at_ms: turn.started_at_ms,
            }),
            last_harness_turn_started_ordinal: self.last_harness_turn_started_ordinal,
            // Filled in by `DurableRelay::operational_state`, which is the
            // only place that can see live processes.
            background_commands: Vec::new(),
            // Provider task knowledge belongs to the current worker process.
            background_work_known: None,
        }
    }

    pub(crate) fn retained_through(&self) -> u64 {
        self.acknowledged_through.min(self.recovery_floor_ordinal)
    }

    pub(crate) fn retained_digest(&self) -> &str {
        if self.acknowledged_through <= self.recovery_floor_ordinal {
            &self.acknowledged_digest
        } else {
            &self.recovery_floor_digest
        }
    }
}

pub(crate) fn ensure_serialized_budget(
    value: &impl Serialize,
    budget: usize,
    description: &str,
) -> Result<()> {
    let size = serde_json::to_vec(value)
        .with_context(|| format!("serialize {description} for size validation"))?
        .len();
    ensure_byte_budget(size, budget, description)
}

pub(crate) fn ensure_byte_budget(size: usize, budget: usize, description: &str) -> Result<()> {
    if size > budget {
        bail!("{description} is too large ({size} bytes; maximum {budget})");
    }
    Ok(())
}

/// One step in a JSON document, used to revisit a located string mutably.
#[derive(Debug, Clone, PartialEq, Eq)]
enum JsonSegment {
    Key(String),
    Index(usize),
}

/// Locate the longest string in a JSON document, with the path to reach it.
fn longest_string_path(value: &Value) -> Option<(Vec<JsonSegment>, usize)> {
    fn walk(
        value: &Value,
        path: &mut Vec<JsonSegment>,
        best: &mut Option<(Vec<JsonSegment>, usize)>,
    ) {
        match value {
            Value::String(text) => {
                if best.as_ref().is_none_or(|(_, length)| text.len() > *length) {
                    *best = Some((path.clone(), text.len()));
                }
            }
            Value::Array(items) => {
                for (index, item) in items.iter().enumerate() {
                    path.push(JsonSegment::Index(index));
                    walk(item, path, best);
                    path.pop();
                }
            }
            Value::Object(entries) => {
                for (key, entry) in entries {
                    path.push(JsonSegment::Key(key.clone()));
                    walk(entry, path, best);
                    path.pop();
                }
            }
            _ => {}
        }
    }

    let mut best = None;
    walk(value, &mut Vec::new(), &mut best);
    best
}

fn string_at_path<'a>(value: &'a mut Value, path: &[JsonSegment]) -> Option<&'a mut String> {
    let mut cursor = value;
    for segment in path {
        cursor = match (segment, cursor) {
            (JsonSegment::Key(key), Value::Object(entries)) => entries.get_mut(key)?,
            (JsonSegment::Index(index), Value::Array(items)) => items.get_mut(*index)?,
            _ => return None,
        };
    }
    match cursor {
        Value::String(text) => Some(text),
        _ => None,
    }
}

/// Shorten `text` to at most `keep` bytes and describe what was dropped.
/// Truncation lands on a character boundary, so the result stays valid UTF-8.
fn truncate_with_marker(text: &mut String, keep: usize) {
    let mut end = keep.min(text.len());
    while end > 0 && !text.is_char_boundary(end) {
        end -= 1;
    }
    let dropped = text.len() - end;
    text.truncate(end);
    text.push_str(&format!("… [mj truncated {dropped} bytes]"));
}

/// Keep at most the last `keep` bytes of `text` and describe what was dropped.
/// The kept part starts on a character boundary, so the result stays valid
/// UTF-8. Returns whether anything was dropped.
///
/// This is the mirror of [`truncate_with_marker`] for output whose end is the
/// interesting part, such as a terminal's tail.
///
/// The Unix worker is the only production caller; the helper stays compiled
/// on Windows so its unit test still builds under `cargo test --no-run`.
#[cfg_attr(not(unix), allow(dead_code))]
pub fn truncate_start_with_marker(text: &mut String, keep: usize) -> bool {
    if text.len() <= keep {
        return false;
    }
    let mut start = text.len() - keep;
    while start < text.len() && !text.is_char_boundary(start) {
        start += 1;
    }
    let dropped = start;
    text.drain(..start);
    text.insert_str(0, &format!("[mj dropped {dropped} earlier bytes]\n"));
    true
}

/// Fit an observation inside `budget` serialized bytes by shortening its
/// largest text payloads.
///
/// The ACP peer decides what the agent said; the relay only decides how much
/// of it one durable event can carry. So an oversized payload is recorded in
/// truncated form rather than rejected — refusing it would strand a live
/// session over a transport limit it cannot see or control.
pub(crate) fn clamp_observation(
    observation: RelayObservation,
    budget: usize,
) -> Result<RelayObservation> {
    let mut size = serde_json::to_vec(&observation)
        .context("measure relay observation")?
        .len();
    if size <= budget {
        return Ok(observation);
    }
    // Only an observation that really has to shrink pays for the JSON tree
    // the truncation pass walks.
    let mut value =
        serde_json::to_value(&observation).context("serialize relay observation for clamping")?;
    let original = size;
    while size > budget {
        let Some((path, length)) = longest_string_path(&value) else {
            break;
        };
        if length <= RELAY_TRUNCATION_FLOOR {
            break;
        }
        let Some(text) = string_at_path(&mut value, &path) else {
            break;
        };
        // Leave room for the marker itself so one pass usually suffices.
        let keep = length
            .saturating_sub(size - budget + 64)
            .max(RELAY_TRUNCATION_FLOOR);
        truncate_with_marker(text, keep);
        size = serde_json::to_vec(&value)
            .context("measure clamped relay observation")?
            .len();
    }
    if size > budget {
        return Ok(RelayObservation::Warning {
            message: format!(
                "dropped an observation that cannot be recorded: {original} bytes exceeds the {budget} byte event budget and its payload is not truncatable"
            ),
        });
    }
    match serde_json::from_value(value) {
        Ok(clamped) => {
            tracing::warn!(
                original,
                clamped = size,
                "truncated an oversized relay observation"
            );
            Ok(clamped)
        }
        Err(error) => Ok(RelayObservation::Warning {
            message: format!(
                "dropped an observation of {original} bytes: it could not be re-read after truncation: {error}"
            ),
        }),
    }
}

/// v1 digest payload: folds `previous_digest` into the hash (the chain link).
/// Its exact field order and serde attributes are load-bearing — changing them
/// would invalidate every stored v1 digest.
#[derive(Serialize)]
struct RelayEventDigestPayload<'a> {
    ordinal: u64,
    previous_digest: &'a str,
    recorded_at_ms: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    command_id: Option<&'a str>,
    observation: &'a RelayObservation,
}

/// v2 digest payload: identical to v1 but with no `previous_digest`, so the
/// digest depends only on the record's own content.
#[derive(Serialize)]
struct RelayEventDigestPayloadV2<'a> {
    ordinal: u64,
    recorded_at_ms: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    command_id: Option<&'a str>,
    observation: &'a RelayObservation,
}

fn digest_over(domain: &[u8], encoded: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(domain);
    hasher.update(encoded);
    format!("{:x}", hasher.finalize())
}

/// Compute the domain-separated SHA-256 digest for a relay event, using the
/// formula that matches the record's format. The `digest` field itself is
/// excluded; for v2 so is `previous_digest`.
pub fn relay_event_digest(event: &RelayEvent) -> Result<String> {
    match event.format {
        RELAY_EVENT_FORMAT_V1 => {
            validate_relay_digest(&event.previous_digest, "previous event digest")?;
            let payload = RelayEventDigestPayload {
                ordinal: event.ordinal,
                previous_digest: &event.previous_digest,
                recorded_at_ms: event.recorded_at_ms,
                command_id: event.command_id.as_deref(),
                observation: &event.observation,
            };
            let encoded =
                serde_json::to_vec(&payload).context("serialize relay event digest payload")?;
            Ok(digest_over(RELAY_EVENT_DIGEST_DOMAIN, &encoded))
        }
        RELAY_EVENT_FORMAT_V2 => {
            if !event.previous_digest.is_empty() {
                bail!(
                    "v2 relay event {} must not carry a previous_digest",
                    event.ordinal
                );
            }
            let payload = RelayEventDigestPayloadV2 {
                ordinal: event.ordinal,
                recorded_at_ms: event.recorded_at_ms,
                command_id: event.command_id.as_deref(),
                observation: &event.observation,
            };
            let encoded =
                serde_json::to_vec(&payload).context("serialize relay event digest payload")?;
            Ok(digest_over(RELAY_EVENT_DIGEST_DOMAIN_V2, &encoded))
        }
        other => bail!(
            "unknown relay event format {other} at event {}",
            event.ordinal
        ),
    }
}

/// Verify an event against the exact previously applied event cursor. This is
/// the shared validation contract for both the relay journal and controller
/// projections.
///
/// Every event is validated by its **own** recomputed digest (self-contained)
/// plus ordinal contiguity. For v1 records the in-record `previous_digest` link
/// to the cursor is also enforced; v2 records carry no link — their continuity
/// to the cursor is proven by the digest anchor at the cursor ordinal
/// (`validate_cursor`) and by the page/frontier endpoint, not by an in-record
/// back-reference. This keeps a corrupt record from invalidating its successors.
pub fn validate_relay_event(
    previous_ordinal: u64,
    previous_digest: &str,
    event: &RelayEvent,
) -> Result<()> {
    validate_relay_digest(previous_digest, "previous cursor digest")?;
    let expected_ordinal = previous_ordinal
        .checked_add(1)
        .ok_or_else(|| anyhow!("relay event ordinal exhausted"))?;
    if event.ordinal != expected_ordinal {
        bail!(
            "relay event gap: expected {expected_ordinal}, found {}",
            event.ordinal
        );
    }
    if event.format == RELAY_EVENT_FORMAT_V1 && event.previous_digest != previous_digest {
        bail!(
            "relay event {} previous digest does not match cursor",
            event.ordinal
        );
    }
    validate_relay_event_self(event)
}

/// Verify a record purely against itself: its `digest` field is well-formed and
/// recomputes to the same value. This is the corruption check for a single
/// record, independent of any neighbour — the unit of trust that lets a corrupt
/// record be isolated instead of poisoning the events around it. It does not
/// check ordinal continuity or (for v1) the chain link; those are the caller's
/// job where a trusted cursor is available.
pub fn validate_relay_event_self(event: &RelayEvent) -> Result<()> {
    validate_relay_digest(&event.digest, "event digest")?;
    let expected_digest = relay_event_digest(event)?;
    if event.digest != expected_digest {
        bail!("relay event {} digest is invalid", event.ordinal);
    }
    Ok(())
}

pub(crate) fn validate_relay_digest(digest: &str, name: &str) -> Result<()> {
    if digest.len() != 64
        || !digest
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
    {
        bail!("{name} must be 64 lowercase hexadecimal characters");
    }
    Ok(())
}

/// Whether applying this observation moves durable relay state beyond the
/// event frontier.
///
/// Transcript observations do not: replaying them from the journal reaches the
/// same snapshot, so appending one need not stage a snapshot copy, re-check the
/// snapshot budgets, or rewrite `relay-state.json`. Every arm here mirrors an
/// arm of [`apply_relay_event`]; `transcript_observations_move_nothing_but_the_frontier`
/// fails if the two ever disagree.
pub(crate) fn observation_changes_state(observation: &RelayObservation) -> bool {
    match observation {
        RelayObservation::AgentInitialized { .. }
        | RelayObservation::SessionOpened { .. }
        | RelayObservation::SessionConfigured { .. }
        | RelayObservation::SessionModesConfigured { .. }
        | RelayObservation::CommandQueued { .. }
        | RelayObservation::CommandStarted { .. }
        | RelayObservation::CommandCompleted { .. }
        | RelayObservation::CommandRejected { .. }
        | RelayObservation::CommandInterrupted { .. }
        | RelayObservation::ConfigurationUpdated { .. }
        | RelayObservation::CheckpointReady { .. }
        // A restart ends any turn the harness started on its own, so it now
        // moves durable state instead of only the frontier.
        | RelayObservation::SessionRestarted
        | RelayObservation::HarnessTurnStarted { .. }
        | RelayObservation::HarnessTurnSettled { .. }
        | RelayObservation::Closing
        | RelayObservation::Closed => true,
        RelayObservation::SessionUpdate { update } => matches!(
            update.as_ref(),
            SessionUpdate::AvailableCommandsUpdate(_)
                | SessionUpdate::ConfigOptionUpdate(_)
                | SessionUpdate::CurrentModeUpdate(_)
        ),
        RelayObservation::PermissionAutoApproved { .. }
        | RelayObservation::ElicitationRequested { .. }
        | RelayObservation::ElicitationResolved { .. }
        | RelayObservation::ElicitationsCleared
        | RelayObservation::Warning { .. }
        | RelayObservation::UserShellOutput { .. }
        | RelayObservation::TerminalOutput { .. }
        | RelayObservation::Notice { .. } => false,
    }
}

pub(crate) fn apply_relay_event(snapshot: &mut RelaySnapshot, event: &RelayEvent) -> Result<()> {
    validate_relay_event(snapshot.latest_ordinal, &snapshot.latest_digest, event)?;
    match &event.observation {
        RelayObservation::AgentInitialized {
            capabilities,
            agent_info,
            ..
        } => {
            snapshot.agent_capabilities = Some(capabilities.clone());
            snapshot.agent_info = agent_info.clone();
        }
        RelayObservation::SessionOpened {
            native_session_id, ..
        } => snapshot.native_session_id = Some(native_session_id.clone()),
        RelayObservation::SessionConfigured { config_options } => {
            snapshot.config_options = config_options.clone();
        }
        RelayObservation::SessionModesConfigured { modes } => {
            snapshot.modes = modes.clone();
        }
        RelayObservation::CommandQueued {
            command_id,
            command,
            created_at_ms,
        } => {
            if cancels_capacity_retry(command) {
                if let Some(retry) = snapshot.capacity_retry.as_mut()
                    && retry.command_id == *command_id
                    && matches!(command, RelayCommand::Prompt { .. })
                {
                    retry.submitted = true;
                } else {
                    snapshot.capacity_retry = None;
                }
            }
            snapshot.handled_commands.insert(
                command_id.clone(),
                HandledRelayCommand {
                    command: command.clone(),
                    accepted_ordinal: event.ordinal,
                    terminal_ordinal: None,
                },
            );
            snapshot.dispatches.insert(
                command_id.clone(),
                RelayDispatchRecord {
                    command: command.clone(),
                    state: RelayDispatchState::Queued,
                },
            );
            // Prompts and configuration changes share one FIFO queue so they
            // reach the agent in the order the user submitted them.
            let payload = match command {
                RelayCommand::Prompt { prompt } => Some(StoredQueuedRelayPayload::Prompt {
                    prompt: prompt.clone(),
                }),
                RelayCommand::SetConfig { key, value } => {
                    Some(StoredQueuedRelayPayload::SetConfig {
                        key: key.clone(),
                        value: value.clone(),
                    })
                }
                _ => None,
            };
            if let Some(payload) = payload {
                snapshot.queued_prompts.push(StoredQueuedRelayCommand {
                    command_id: command_id.clone(),
                    payload,
                    created_at_ms: *created_at_ms,
                });
            }
            if let RelayCommand::RunUserShell { command } = command {
                snapshot.active_user_shells.insert(
                    command_id.clone(),
                    ActiveUserShell {
                        command_id: command_id.clone(),
                        command: command.clone(),
                        created_at_ms: *created_at_ms,
                        started_at_ms: None,
                    },
                );
            }
            if matches!(command, RelayCommand::Close { .. }) {
                snapshot.execution = RelayExecutionState::Closing;
            }
        }
        RelayObservation::CommandStarted {
            command_id,
            started_at_ms,
        } => {
            let dispatch = snapshot
                .dispatches
                .get_mut(command_id)
                .ok_or_else(|| anyhow!("started unknown relay command {command_id}"))?;
            dispatch.state = RelayDispatchState::Pending;
            match &dispatch.command {
                RelayCommand::Prompt { .. } => {
                    let index = snapshot
                        .queued_prompts
                        .iter()
                        .position(|queued| queued.command_id == *command_id)
                        .ok_or_else(|| anyhow!("started prompt {command_id} was not queued"))?;
                    let queued = snapshot.queued_prompts.remove(index);
                    let StoredQueuedRelayPayload::Prompt { prompt } = queued.payload else {
                        bail!("queued command {command_id} is not a prompt");
                    };
                    snapshot.execution = RelayExecutionState::Running;
                    snapshot.activity_turn_started_at_ms = Some(*started_at_ms);
                    snapshot.active_prompt = Some(StoredActiveRelayPrompt {
                        command_id: queued.command_id,
                        prompt,
                        created_at_ms: queued.created_at_ms,
                        started_at_ms: *started_at_ms,
                    });
                }
                // A configuration change leaves the queue when it starts, but
                // the ACP session stays idle: it applies between turns.
                RelayCommand::SetConfig { .. } => {
                    let index = snapshot
                        .queued_prompts
                        .iter()
                        .position(|queued| queued.command_id == *command_id)
                        .ok_or_else(|| {
                            anyhow!("started configuration change {command_id} was not queued")
                        })?;
                    snapshot.queued_prompts.remove(index);
                }
                RelayCommand::Close { .. } => snapshot.execution = RelayExecutionState::Closing,
                RelayCommand::RunUserShell { .. } => {
                    let shell = snapshot
                        .active_user_shells
                        .get_mut(command_id)
                        .ok_or_else(|| anyhow!("started unknown user shell {command_id}"))?;
                    shell.started_at_ms = Some(*started_at_ms);
                }
                RelayCommand::BeginCheckpoint { .. } => {
                    if snapshot.checkpoint_barrier.is_some() {
                        bail!("checkpoint barrier started while another barrier was active");
                    }
                    snapshot.checkpoint_barrier = Some(command_id.clone());
                    snapshot.checkpoint_ready_through = None;
                    snapshot.checkpoint_ready_digest = None;
                }
                _ => {}
            }
        }
        RelayObservation::CommandCompleted {
            command_id,
            outcome,
        } => {
            let command = snapshot
                .dispatches
                .get(command_id)
                .ok_or_else(|| anyhow!("completed unknown relay command {command_id}"))?
                .command
                .clone();
            snapshot
                .dispatches
                .get_mut(command_id)
                .expect("dispatch disappeared")
                .state = RelayDispatchState::Completed;
            snapshot
                .handled_commands
                .get_mut(command_id)
                .ok_or_else(|| anyhow!("completed command {command_id} is not in the ledger"))?
                .terminal_ordinal = Some(event.ordinal);
            if let RelayCommandOutcome::Prompt { stop_reason } = outcome {
                let accepted = snapshot.handled_commands[command_id].accepted_ordinal;
                let superseded = snapshot.handled_commands.values().any(|handled| {
                    handled.accepted_ordinal > accepted && cancels_capacity_retry(&handled.command)
                });
                let attempt = snapshot
                    .capacity_retry
                    .as_ref()
                    .filter(|retry| retry.command_id == *command_id)
                    .map_or(1, |retry| retry.attempt.saturating_add(1));
                snapshot.capacity_retry = if stop_reason == CAPACITY_STOP_REASON && !superseded {
                    Some(CapacityRetry::new(
                        attempt,
                        event.ordinal,
                        event.recorded_at_ms,
                    ))
                } else {
                    None
                };
            }
            match (command, outcome) {
                (RelayCommand::Prompt { .. }, RelayCommandOutcome::Prompt { .. }) => {
                    if snapshot
                        .active_prompt
                        .as_ref()
                        .map(|active| &active.command_id)
                        == Some(command_id)
                    {
                        snapshot.active_prompt = None;
                    }
                    // A prompt result means the SDK reached a turn boundary,
                    // so whatever the harness had started on its own is over.
                    snapshot.harness_turn = None;
                    if snapshot.execution == RelayExecutionState::Running {
                        snapshot.execution = RelayExecutionState::Idle;
                    }
                    if snapshot
                        .pending_prompt_context
                        .as_ref()
                        .and_then(|context| context.attached_command_id.as_deref())
                        == Some(command_id.as_str())
                    {
                        snapshot.pending_prompt_context = None;
                    }
                    snapshot.pending_user_shell_contexts.retain(|context| {
                        context.attached_command_id.as_deref() != Some(command_id.as_str())
                    });
                }
                (RelayCommand::RunUserShell { .. }, RelayCommandOutcome::UserShell { result }) => {
                    snapshot.active_user_shells.remove(command_id);
                    let accepted_ordinal = snapshot
                        .handled_commands
                        .get(command_id)
                        .ok_or_else(|| anyhow!("completed user shell is not in the ledger"))?
                        .accepted_ordinal;
                    snapshot
                        .pending_user_shell_contexts
                        .push(PendingUserShellContext {
                            shell_command_id: command_id.clone(),
                            accepted_ordinal,
                            text: result.prompt_context(),
                            attached_command_id: None,
                        });
                }
                (RelayCommand::CancelUserShell { .. }, RelayCommandOutcome::UserShellCancelled) => {
                }
                (
                    RelayCommand::RemoveQueuedPrompt { queued_command_id },
                    RelayCommandOutcome::QueueChanged {
                        removed_command_ids,
                    },
                ) => {
                    let expected = snapshot
                        .queued_prompts
                        .iter()
                        .any(|queued| queued.command_id == queued_command_id)
                        .then_some(vec![queued_command_id]);
                    if expected.as_deref() != Some(removed_command_ids.as_slice()) {
                        bail!("removed queue outcome does not match the durable queue");
                    }
                    terminalize_removed_prompts(snapshot, removed_command_ids, event.ordinal)?;
                }
                (
                    RelayCommand::ClearQueuedPrompts,
                    RelayCommandOutcome::QueueChanged {
                        removed_command_ids,
                    },
                ) => {
                    let expected: Vec<String> = snapshot
                        .queued_prompts
                        .iter()
                        .map(|queued| queued.command_id.clone())
                        .collect();
                    if expected != *removed_command_ids {
                        bail!("cleared queue outcome does not match the durable queue");
                    }
                    terminalize_removed_prompts(snapshot, removed_command_ids, event.ordinal)?;
                }
                (RelayCommand::SetConfig { key, value }, RelayCommandOutcome::Configured) => {
                    snapshot.config.insert(key.clone(), value.clone());
                    crate::hel_acp::AcceptedSessionConfig::record_completed(
                        &mut snapshot.config,
                        &key,
                        &value,
                        &snapshot.config_options,
                    );
                }
                (RelayCommand::SetSessionMode { mode_id }, RelayCommandOutcome::SessionModeSet) => {
                    snapshot.config.insert("mode".to_owned(), mode_id);
                }
                (RelayCommand::Cancel, RelayCommandOutcome::Cancelled)
                | (RelayCommand::CancelTurn, RelayCommandOutcome::Cancelled) => {}
                (RelayCommand::Cancel, RelayCommandOutcome::Steered { queued_command_id }) => {
                    let queued = snapshot
                        .queued_prompts
                        .first()
                        .ok_or_else(|| anyhow!("steered prompt is no longer queued"))?;
                    if queued.command_id != *queued_command_id
                        || !matches!(queued.payload, StoredQueuedRelayPayload::Prompt { .. })
                    {
                        bail!("steered prompt is not the queued prompt head");
                    }
                    let target = snapshot
                        .dispatches
                        .get_mut(queued_command_id)
                        .ok_or_else(|| anyhow!("steered unknown queued prompt"))?;
                    if target.state != RelayDispatchState::Queued
                        || !matches!(target.command, RelayCommand::Prompt { .. })
                    {
                        bail!("steered target is not a queued prompt");
                    }
                    target.state = RelayDispatchState::Completed;
                    snapshot
                        .handled_commands
                        .get_mut(queued_command_id)
                        .ok_or_else(|| anyhow!("steered prompt is not in the ledger"))?
                        .terminal_ordinal = Some(event.ordinal);
                    snapshot.queued_prompts.remove(0);
                    if snapshot
                        .pending_prompt_context
                        .as_ref()
                        .and_then(|context| context.attached_command_id.as_deref())
                        == Some(queued_command_id.as_str())
                    {
                        snapshot.pending_prompt_context = None;
                    }
                    snapshot.pending_user_shell_contexts.retain(|context| {
                        context.attached_command_id.as_deref() != Some(queued_command_id.as_str())
                    });
                }
                (RelayCommand::Close { .. }, RelayCommandOutcome::Closed) => {
                    snapshot.execution = RelayExecutionState::Closed;
                    snapshot.active_prompt = None;
                }
                (
                    RelayCommand::CompleteCheckpoint { barrier_command_id },
                    RelayCommandOutcome::CheckpointCompleted,
                ) => {
                    if snapshot.checkpoint_barrier.as_deref() != Some(&barrier_command_id) {
                        bail!("checkpoint completion does not match the active barrier");
                    }
                    let ready_through = snapshot
                        .checkpoint_ready_through
                        .ok_or_else(|| anyhow!("checkpoint barrier was not ready"))?;
                    let ready_digest = snapshot
                        .checkpoint_ready_digest
                        .clone()
                        .ok_or_else(|| anyhow!("checkpoint barrier ready digest is missing"))?;
                    snapshot.recovery_floor_ordinal = ready_through;
                    snapshot.recovery_floor_digest = ready_digest;
                    snapshot.checkpoint_barrier = None;
                    snapshot.checkpoint_ready_through = None;
                    snapshot.checkpoint_ready_digest = None;
                    if let Some(barrier) = snapshot.dispatches.get_mut(&barrier_command_id) {
                        barrier.state = RelayDispatchState::Completed;
                    }
                    if let Some(barrier) = snapshot.handled_commands.get_mut(&barrier_command_id) {
                        barrier.terminal_ordinal = Some(event.ordinal);
                    }
                }
                (
                    RelayCommand::ReleaseCheckpoint { barrier_command_id },
                    RelayCommandOutcome::CheckpointReleased,
                ) => {
                    if snapshot.checkpoint_barrier.as_deref() != Some(&barrier_command_id) {
                        bail!("checkpoint release does not match the active barrier");
                    }
                    if snapshot.checkpoint_ready_through.is_none() {
                        bail!("checkpoint barrier was not ready");
                    }
                    // Dispatch resumes, but the recovery floor stays where the
                    // last installed archive left it: nothing yet proves this
                    // archive reached the controller's disk.
                    snapshot.checkpoint_barrier = None;
                    snapshot.checkpoint_ready_through = None;
                    snapshot.checkpoint_ready_digest = None;
                    if let Some(barrier) = snapshot.dispatches.get_mut(&barrier_command_id) {
                        barrier.state = RelayDispatchState::Completed;
                    }
                    if let Some(barrier) = snapshot.handled_commands.get_mut(&barrier_command_id) {
                        barrier.terminal_ordinal = Some(event.ordinal);
                    }
                }
                (
                    RelayCommand::AdvanceRecoveryFloor { through },
                    RelayCommandOutcome::RecoveryFloorAdvanced,
                ) => {
                    if through.ordinal < snapshot.recovery_floor_ordinal {
                        bail!("recovery floor cannot move back");
                    }
                    snapshot.recovery_floor_ordinal = through.ordinal;
                    snapshot.recovery_floor_digest = through.digest;
                }
                (RelayCommand::RecordNotice { .. }, RelayCommandOutcome::NoticeRecorded) => {}
                (RelayCommand::BeginCheckpoint { .. }, _) => {
                    bail!("checkpoint barriers complete through checkpoint-ready")
                }
                (command, outcome) => {
                    bail!(
                        "relay command {:?} has incompatible completion outcome {outcome:?}",
                        command.kind()
                    )
                }
            }
        }
        RelayObservation::CommandRejected {
            command_id,
            command: observed_command,
            message,
        }
        | RelayObservation::CommandInterrupted {
            command_id,
            command: observed_command,
            message,
        } => {
            let state = if matches!(event.observation, RelayObservation::CommandRejected { .. }) {
                RelayDispatchState::Rejected
            } else {
                RelayDispatchState::Interrupted
            };
            let command = snapshot
                .dispatches
                .get(command_id)
                .ok_or_else(|| anyhow!("terminated unknown relay command {command_id}"))?
                .command
                .clone();
            if command.kind() != *observed_command {
                bail!("terminated command {command_id} has the wrong command identity");
            }
            snapshot
                .dispatches
                .get_mut(command_id)
                .expect("dispatch disappeared")
                .state = state;
            snapshot
                .handled_commands
                .get_mut(command_id)
                .ok_or_else(|| anyhow!("terminated command {command_id} is not in the ledger"))?
                .terminal_ordinal = Some(event.ordinal);
            snapshot
                .queued_prompts
                .retain(|queued| queued.command_id != *command_id);
            snapshot.active_user_shells.remove(command_id);
            if let RelayCommand::RunUserShell { command } = &command {
                let accepted_ordinal = snapshot
                    .handled_commands
                    .get(command_id)
                    .expect("terminated shell command disappeared from the ledger")
                    .accepted_ordinal;
                let result = UserShellResult {
                    command: command.clone(),
                    stdout: String::new(),
                    stderr: String::new(),
                    stdout_truncated: false,
                    stderr_truncated: false,
                    exit_code: None,
                    signal: None,
                    duration_ms: 0,
                    status: if state == RelayDispatchState::Rejected {
                        UserShellStatus::Failed
                    } else {
                        UserShellStatus::Interrupted
                    },
                    error: Some(message.clone()),
                };
                snapshot
                    .pending_user_shell_contexts
                    .push(PendingUserShellContext {
                        shell_command_id: command_id.clone(),
                        accepted_ordinal,
                        text: result.prompt_context(),
                        attached_command_id: None,
                    });
            }
            if snapshot
                .active_prompt
                .as_ref()
                .map(|active| &active.command_id)
                == Some(command_id)
            {
                snapshot.active_prompt = None;
                snapshot.harness_turn = None;
                snapshot.execution = RelayExecutionState::Idle;
            }
            if snapshot
                .pending_prompt_context
                .as_ref()
                .and_then(|context| context.attached_command_id.as_deref())
                == Some(command_id.as_str())
            {
                snapshot
                    .pending_prompt_context
                    .as_mut()
                    .expect("pending prompt context disappeared")
                    .attached_command_id = None;
            }
            for context in &mut snapshot.pending_user_shell_contexts {
                if context.attached_command_id.as_deref() == Some(command_id.as_str()) {
                    context.attached_command_id = None;
                }
            }
            if matches!(command, RelayCommand::BeginCheckpoint { .. })
                && snapshot.checkpoint_barrier.as_deref() == Some(command_id)
            {
                snapshot.checkpoint_barrier = None;
                snapshot.checkpoint_ready_through = None;
                snapshot.checkpoint_ready_digest = None;
            }
            if matches!(command, RelayCommand::Close { .. })
                && snapshot.execution == RelayExecutionState::Closing
            {
                snapshot.execution = RelayExecutionState::Idle;
            }
        }
        RelayObservation::ConfigurationUpdated { key, value } => {
            snapshot.config.insert(key.clone(), value.clone());
        }
        RelayObservation::CheckpointReady {
            command_id,
            through,
        } => {
            let Some(dispatch) = snapshot.dispatches.get(command_id) else {
                bail!("checkpoint ready for unknown command {command_id}");
            };
            if !matches!(dispatch.command, RelayCommand::BeginCheckpoint { .. }) {
                bail!("checkpoint ready for non-barrier command {command_id}");
            }
            if snapshot.checkpoint_barrier.as_deref() != Some(command_id) {
                bail!("checkpoint ready does not match the active barrier");
            }
            if *through != event.ordinal {
                bail!("checkpoint ready frontier does not match its event ordinal");
            }
            snapshot.checkpoint_ready_through = Some(*through);
            snapshot.checkpoint_ready_digest = Some(event.digest.clone());
        }
        RelayObservation::HarnessTurnStarted { started_at_ms } => {
            snapshot.activity_turn_started_at_ms = Some(*started_at_ms);
            snapshot.harness_turn = Some(StoredHarnessTurn {
                started_at_ms: *started_at_ms,
                first_ordinal: event.ordinal,
            });
            snapshot.last_harness_turn_started_ordinal = Some(event.ordinal);
            if snapshot.execution == RelayExecutionState::Idle {
                snapshot.execution = RelayExecutionState::Running;
            }
        }
        RelayObservation::HarnessTurnSettled { .. } => {
            snapshot.harness_turn = None;
            if snapshot.active_prompt.is_none()
                && snapshot.execution == RelayExecutionState::Running
            {
                snapshot.execution = RelayExecutionState::Idle;
            }
        }
        // The control plane behind the session was replaced, so a turn the
        // harness had started on its own no longer exists. Both callers record
        // this with no prompt in flight.
        RelayObservation::SessionRestarted => {
            if snapshot.harness_turn.take().is_some()
                && snapshot.active_prompt.is_none()
                && snapshot.execution == RelayExecutionState::Running
            {
                snapshot.execution = RelayExecutionState::Idle;
            }
        }
        RelayObservation::Closing => {
            snapshot.capacity_retry = None;
            snapshot.harness_turn = None;
            snapshot.execution = RelayExecutionState::Closing;
        }
        RelayObservation::Closed => {
            snapshot.capacity_retry = None;
            snapshot.activity_turn_started_at_ms = None;
            snapshot.harness_turn = None;
            snapshot.execution = RelayExecutionState::Closed;
            snapshot.active_prompt = None;
        }
        RelayObservation::SessionUpdate { update } => match update.as_ref() {
            SessionUpdate::AvailableCommandsUpdate(update) => {
                snapshot.available_commands = update.available_commands.clone();
            }
            SessionUpdate::ConfigOptionUpdate(update) => {
                snapshot.config_options = update.config_options.clone();
            }
            SessionUpdate::CurrentModeUpdate(update) => {
                if let Some(modes) = snapshot.modes.as_mut() {
                    modes.current_mode_id = update.current_mode_id.clone();
                }
                snapshot
                    .config
                    .insert("mode".to_owned(), update.current_mode_id.to_string());
            }
            _ => {}
        },
        RelayObservation::PermissionAutoApproved { .. }
        | RelayObservation::ElicitationRequested { .. }
        | RelayObservation::ElicitationResolved { .. }
        | RelayObservation::ElicitationsCleared
        | RelayObservation::Warning { .. }
        | RelayObservation::UserShellOutput { .. }
        | RelayObservation::TerminalOutput { .. }
        | RelayObservation::Notice { .. } => {}
    }
    snapshot.latest_ordinal = event.ordinal;
    snapshot.latest_digest = event.digest.clone();
    Ok(())
}

/// Whether finishing this relay-local command can let journal GC drop history.
/// Only a recovery-floor move does; releasing a barrier deliberately leaves the
/// floor where an installed archive left it.
pub(crate) fn releases_history(command: &RelayCommand) -> bool {
    matches!(
        command,
        RelayCommand::CompleteCheckpoint { .. } | RelayCommand::AdvanceRecoveryFloor { .. }
    )
}

fn terminalize_removed_prompts(
    snapshot: &mut RelaySnapshot,
    removed_command_ids: &[String],
    terminal_ordinal: u64,
) -> Result<()> {
    for command_id in removed_command_ids {
        let dispatch = snapshot
            .dispatches
            .get_mut(command_id)
            .ok_or_else(|| anyhow!("removed unknown queued command {command_id}"))?;
        if !dispatch.command.is_queue_entry() || dispatch.state != RelayDispatchState::Queued {
            bail!("removed command {command_id} is not a queued command");
        }
        dispatch.state = RelayDispatchState::Rejected;
        snapshot
            .handled_commands
            .get_mut(command_id)
            .ok_or_else(|| anyhow!("removed command {command_id} is not in the ledger"))?
            .terminal_ordinal = Some(terminal_ordinal);
    }
    snapshot.queued_prompts.retain(|queued| {
        !removed_command_ids
            .iter()
            .any(|command_id| command_id == &queued.command_id)
    });
    Ok(())
}

pub(crate) fn validate_relay_snapshot_frontiers(snapshot: &RelaySnapshot) -> Result<()> {
    if snapshot.acknowledged_through > snapshot.latest_ordinal {
        bail!("relay acknowledgement is ahead of the event frontier");
    }
    if snapshot.recovery_floor_ordinal > snapshot.latest_ordinal {
        bail!("relay recovery floor is ahead of the event frontier");
    }
    validate_relay_digest(&snapshot.latest_digest, "relay latest digest")?;
    validate_relay_digest(
        &snapshot.acknowledged_digest,
        "relay acknowledgement digest",
    )?;
    validate_relay_digest(
        &snapshot.recovery_floor_digest,
        "relay recovery floor digest",
    )?;
    if (snapshot.latest_ordinal == 0) != (snapshot.latest_digest == RELAY_EVENT_GENESIS_DIGEST) {
        bail!("relay latest frontier and genesis digest disagree");
    }
    if (snapshot.acknowledged_through == 0)
        != (snapshot.acknowledged_digest == RELAY_EVENT_GENESIS_DIGEST)
    {
        bail!("relay acknowledgement frontier and genesis digest disagree");
    }
    if (snapshot.recovery_floor_ordinal == 0)
        != (snapshot.recovery_floor_digest == RELAY_EVENT_GENESIS_DIGEST)
    {
        bail!("relay recovery floor and genesis digest disagree");
    }
    Ok(())
}

/// Explicit user work and lifecycle admission supersede automated recovery.
fn cancels_capacity_retry(command: &RelayCommand) -> bool {
    matches!(
        command,
        RelayCommand::Prompt { .. }
            | RelayCommand::Cancel
            | RelayCommand::CancelTurn
            | RelayCommand::SetConfig { .. }
            | RelayCommand::SetSessionMode { .. }
            | RelayCommand::Close { .. }
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hel_worker::test_support::*;
    use crate::hel_worker::{
        DurableRelay, RELAY_COMMAND_BYTE_BUDGET, RELAY_EVENT_BYTE_BUDGET, RELAY_STATE_BYTE_BUDGET,
        RelayErrorCode, RelayProtocolError, RelayRequest, RelayResponseBody,
    };

    #[test]
    fn cancel_turn_is_reserved_for_relay_protocol_v7() {
        assert_eq!(RelayCommand::CancelTurn.minimum_protocol(), 7);
        assert_eq!(RelayCommand::Cancel.minimum_protocol(), 1);
    }

    /// Every way a session can still be holding work, each on its own, plus
    /// the one state in which replacing its worker destroys nothing.
    #[test]
    fn a_session_is_quiet_only_when_nothing_it_owns_is_in_flight() {
        let temp = tempfile::tempdir().unwrap();
        let relay = DurableRelay::open(temp.path(), SESSION, "1.0.0").unwrap();
        let mut quiet = relay.operational_state();
        assert!(!quiet.is_quiet(), "startup is still in flight");
        quiet.acp_ready = Some(true);
        assert!(
            quiet.is_quiet(),
            "a ready idle relay owns nothing: {quiet:?}"
        );

        type MakeBusy = fn(&mut RelayOperationalState);
        let busy: Vec<(&str, MakeBusy)> = vec![
            (
                "a prompt is running",
                (|state| state.execution = RelayExecutionState::Running),
            ),
            (
                "a prompt is in flight",
                (|state| {
                    state.active_prompt = Some(ActiveRelayPrompt {
                        command_id: "prompt-1".into(),
                        created_at_ms: 1,
                        started_at_ms: 2,
                    });
                }),
            ),
            (
                "the harness started a turn of its own",
                (|state| {
                    state.harness_turn = Some(HarnessTurn { started_at_ms: 1 });
                }),
            ),
            (
                "a prompt is queued behind the current one",
                (|state| {
                    state.queued_prompts = vec![QueuedRelayPrompt {
                        command_id: "prompt-2".into(),
                        created_at_ms: 1,
                    }];
                }),
            ),
            (
                "a user shell is open",
                (|state| {
                    state.active_user_shells = vec![ActiveUserShell {
                        command_id: "shell-1".into(),
                        command: "top".into(),
                        created_at_ms: 1,
                        started_at_ms: Some(1),
                    }];
                }),
            ),
            (
                "an agent terminal is live",
                (|state| {
                    state.active_agent_terminals = vec![ActiveAgentTerminal {
                        terminal_id: "term-1".into(),
                        command: "sleep 600".into(),
                        started_at_ms: 1,
                    }];
                }),
            ),
            (
                "the agent left a command running",
                (|state| {
                    state.background_commands = vec![BackgroundCommand {
                        id: "task-1".into(),
                        started_at_ms: 1,
                        command: "sleep 600".into(),
                        can_stop: false,
                    }];
                }),
            ),
            (
                "a foreground tool is still in progress",
                (|state| state.foreground_tool_started_at_ms = Some(1)),
            ),
            (
                "a checkpoint barrier is waiting",
                (|state| state.checkpoint_barrier = Some("checkpoint-1".into())),
            ),
        ];
        for (reason, make_busy) in busy {
            let mut state = quiet.clone();
            make_busy(&mut state);
            assert!(!state.is_quiet(), "{reason}");
        }
    }

    #[test]
    fn relay_operational_state_tracks_mutable_acp_options_and_commands() {
        use agent_client_protocol::schema::v1::{
            AvailableCommandsUpdate, ConfigOptionUpdate, CurrentModeUpdate,
            SessionConfigSelectOption, SessionMode, SessionModeState,
        };

        let temp = tempfile::tempdir().unwrap();
        let mut relay = DurableRelay::open(temp.path(), SESSION, "1.0.0").unwrap();
        let option = SessionConfigOption::select(
            "thinking",
            "Thinking",
            "on",
            vec![SessionConfigSelectOption::new("on", "On")],
        );
        relay
            .record_session_update(SessionUpdate::ConfigOptionUpdate(ConfigOptionUpdate::new(
                vec![option.clone()],
            )))
            .unwrap();
        relay
            .record_observation(RelayObservation::SessionModesConfigured {
                modes: Some(SessionModeState::new(
                    "default",
                    vec![
                        SessionMode::new("default", "Default"),
                        SessionMode::new("plan", "Plan"),
                    ],
                )),
            })
            .unwrap();
        relay
            .record_session_update(SessionUpdate::CurrentModeUpdate(CurrentModeUpdate::new(
                "plan",
            )))
            .unwrap();
        relay
            .record_session_update(SessionUpdate::AvailableCommandsUpdate(
                AvailableCommandsUpdate::new(vec![AvailableCommand::new(
                    "review",
                    "Review the current work",
                )]),
            ))
            .unwrap();

        let state = relay.operational_state();
        assert_eq!(state.config_options, vec![option]);
        assert_eq!(state.config["mode"], "plan");
        assert_eq!(
            state.modes.unwrap().current_mode_id.to_string(),
            "plan",
            "current_mode_update keeps the legacy catalogue synchronized"
        );
        assert_eq!(state.available_commands[0].name, "review");
    }

    #[test]
    fn snapshots_without_legacy_modes_still_deserialize() {
        let snapshot = RelaySnapshot::new(SESSION.into());
        let mut encoded = serde_json::to_value(snapshot).unwrap();
        encoded.as_object_mut().unwrap().remove("modes");

        let restored: RelaySnapshot = serde_json::from_value(encoded).unwrap();

        assert_eq!(restored.modes, None);
    }

    #[test]
    fn native_session_readiness_requires_current_acp_session() {
        let mut state = RelaySnapshot::new(SESSION.into()).operational_state();
        state.native_session_id = Some("restored-native-session".into());
        state.acp_ready = Some(false);
        assert!(!state.native_session_is_ready());

        state.acp_ready = Some(true);
        assert!(state.native_session_is_ready());

        state.execution = RelayExecutionState::Closed;
        assert!(!state.native_session_is_ready());
    }

    #[test]
    fn legacy_operational_state_without_acp_readiness_is_ready() {
        let mut state = RelaySnapshot::new(SESSION.into()).operational_state();
        state.native_session_id = Some("legacy-native-session".into());
        assert_eq!(state.acp_ready, None);
        let mut encoded = serde_json::to_value(state).unwrap();
        encoded.as_object_mut().unwrap().remove("acp_ready");

        let restored: RelayOperationalState = serde_json::from_value(encoded).unwrap();

        assert_eq!(restored.acp_ready, None);
        assert!(restored.native_session_is_ready());
    }

    #[test]
    fn kimi_replacement_requires_current_background_work_knowledge() {
        let mut state = RelaySnapshot::new(SESSION.into()).operational_state();
        state.native_session_id = Some("native-session".into());
        state.acp_ready = Some(true);

        assert!(state.is_quiet());
        assert!(state.safe_to_replace(HarnessKind::Codex));
        assert!(
            !state.safe_to_replace(HarnessKind::Kimi),
            "an older Kimi worker cannot prove provider tasks are absent"
        );

        state.background_work_known = Some(false);
        assert!(!state.is_quiet());
        assert!(!state.safe_to_replace(HarnessKind::Kimi));

        state.background_work_known = Some(true);
        assert!(state.is_quiet());
        assert!(state.safe_to_replace(HarnessKind::Kimi));
    }

    #[test]
    fn kimi_checkpoint_requires_known_empty_background_work() {
        let mut state = RelaySnapshot::new(SESSION.into()).operational_state();
        assert!(state.safe_for_checkpoint(HarnessKind::Codex));
        assert!(
            !state.safe_for_checkpoint(HarnessKind::Kimi),
            "an older Kimi worker cannot prove provider tasks are absent"
        );

        state.background_work_known = Some(false);
        assert!(!state.safe_for_checkpoint(HarnessKind::Kimi));

        state.background_work_known = Some(true);
        assert!(state.safe_for_checkpoint(HarnessKind::Kimi));
        state.background_commands.push(BackgroundCommand {
            id: "kimi:agent-1".into(),
            started_at_ms: 1,
            command: "background agent".into(),
            can_stop: false,
        });
        assert!(!state.safe_for_checkpoint(HarnessKind::Kimi));
    }

    #[test]
    fn initializing_operational_state_is_not_quiet() {
        let mut state = RelaySnapshot::new(SESSION.into()).operational_state();
        state.acp_ready = Some(false);

        assert!(!state.is_quiet());
    }

    /// Transcript observations skip the staged snapshot copy and its budget
    /// checks, which is only sound while applying one really moves nothing but
    /// the frontier. Anything that can grow the snapshot must classify as a
    /// state move so its budget is still checked before it is journaled.
    #[test]
    fn transcript_observations_move_nothing_but_the_frontier() {
        use agent_client_protocol::schema::v1::{
            AvailableCommandsUpdate, ContentBlock, ContentChunk,
        };

        let transcript = [
            RelayObservation::Warning {
                message: "warned".into(),
            },
            RelayObservation::Notice {
                message: "noticed".into(),
            },
            RelayObservation::TerminalOutput {
                terminal_id: "terminal-1".into(),
                output: "output".into(),
                truncated: false,
                exit_code: Some(0),
                signal: None,
            },
            RelayObservation::PermissionAutoApproved {
                option_id: "allow".into(),
                option_name: "Allow".into(),
            },
            RelayObservation::ElicitationRequested {
                request: crate::hel_elicitation::ElicitationRequest {
                    id: "elicitation-1".into(),
                    message: "confirm".into(),
                    title: None,
                    description: None,
                    fields: Vec::new(),
                },
            },
            RelayObservation::ElicitationResolved {
                elicitation_id: "elicitation-1".into(),
                action: "accept".into(),
            },
            RelayObservation::ElicitationsCleared,
            RelayObservation::SessionUpdate {
                update: Box::new(SessionUpdate::AgentMessageChunk(ContentChunk::new(
                    ContentBlock::from("streamed"),
                ))),
            },
        ];
        for observation in transcript {
            assert!(
                !observation_changes_state(&observation),
                "{observation:?} is classified as a state move"
            );
            let mut snapshot = RelaySnapshot::new(SESSION.to_owned());
            let event = RelayEvent {
                format: RELAY_EVENT_FORMAT_V1,
                ordinal: 1,
                previous_digest: RELAY_EVENT_GENESIS_DIGEST.to_owned(),
                digest: String::new(),
                recorded_at_ms: 7,
                command_id: None,
                observation,
            };
            let event = RelayEvent {
                digest: relay_event_digest(&event).unwrap(),
                ..event
            };
            let mut expected = snapshot.clone();
            expected.latest_ordinal = event.ordinal;
            expected.latest_digest.clone_from(&event.digest);
            apply_relay_event(&mut snapshot, &event).unwrap();
            assert_eq!(
                snapshot, expected,
                "{:?} changed durable state",
                event.observation
            );
        }

        for observation in [
            RelayObservation::CommandQueued {
                command_id: "queued-command".into(),
                command: prompt("grow the snapshot"),
                created_at_ms: 7,
            },
            RelayObservation::SessionUpdate {
                update: Box::new(SessionUpdate::AvailableCommandsUpdate(
                    AvailableCommandsUpdate::new(vec![AvailableCommand::new(
                        "review",
                        "Review the current work",
                    )]),
                )),
            },
            // A harness-initiated turn moves execution state, and a restart
            // ends one, so all three must be applied through a staged snapshot
            // rather than appended as transcript-only frontier moves.
            RelayObservation::HarnessTurnStarted { started_at_ms: 7 },
            RelayObservation::HarnessTurnSettled {
                origin: Some("task-notification".into()),
                prompt_in_flight: false,
            },
            RelayObservation::SessionRestarted,
        ] {
            assert!(
                observation_changes_state(&observation),
                "{observation:?} can grow the snapshot and must be budget-checked"
            );
        }
    }

    #[test]
    fn v1_events_round_trip_byte_identically_and_v2_omits_the_chain() {
        let observation = || RelayObservation::Warning {
            message: "hi".into(),
        };

        // v1: no `format` key on the wire, keeps previous_digest, chains to its
        // cursor. Existing journals stay byte-for-byte identical.
        let mut v1 = RelayEvent {
            format: RELAY_EVENT_FORMAT_V1,
            ordinal: 1,
            previous_digest: RELAY_EVENT_GENESIS_DIGEST.to_owned(),
            digest: String::new(),
            recorded_at_ms: 42,
            command_id: None,
            observation: observation(),
        };
        v1.digest = relay_event_digest(&v1).unwrap();
        let v1_json = serde_json::to_string(&v1).unwrap();
        assert!(
            !v1_json.contains("\"format\""),
            "v1 must not write a format key: {v1_json}"
        );
        assert!(v1_json.contains("previous_digest"));
        validate_relay_event(0, RELAY_EVENT_GENESIS_DIGEST, &v1).unwrap();

        // v2: tags its format, carries no chain link, and self-validates
        // regardless of the cursor digest.
        let mut v2 = RelayEvent {
            format: RELAY_EVENT_FORMAT_V2,
            ordinal: 1,
            previous_digest: String::new(),
            digest: String::new(),
            recorded_at_ms: 42,
            command_id: None,
            observation: observation(),
        };
        v2.digest = relay_event_digest(&v2).unwrap();
        let v2_json = serde_json::to_string(&v2).unwrap();
        assert!(
            v2_json.contains("\"format\":2"),
            "v2 must tag its format: {v2_json}"
        );
        assert!(
            !v2_json.contains("previous_digest"),
            "v2 must not write a chain link: {v2_json}"
        );
        validate_relay_event(0, RELAY_EVENT_GENESIS_DIGEST, &v2).unwrap();
        validate_relay_event(0, &"a".repeat(64), &v2)
            .expect("a v2 event has no in-record link, so any cursor digest is accepted");

        // Same ordinal + content, different format → different digest (domain
        // separation + payload), so v1 and v2 never collide.
        assert_ne!(v1.digest, v2.digest);

        // Round-trip both, and confirm an old record with no `format` key reads
        // as v1.
        let v1_back: RelayEvent = serde_json::from_str(&v1_json).unwrap();
        assert_eq!(v1_back, v1);
        let v2_back: RelayEvent = serde_json::from_str(&v2_json).unwrap();
        assert_eq!(v2_back, v2);
        assert_eq!(v2_back.previous_digest, "");
        let legacy: RelayEvent =
            serde_json::from_str(r#"{"ordinal":1,"previous_digest":"","digest":"x","recorded_at_ms":0,"observation":{"type":"warning","data":{"message":"m"}}}"#)
                .unwrap();
        assert_eq!(legacy.format, RELAY_EVENT_FORMAT_V1);
    }

    #[test]
    fn queue_entries_written_before_config_changes_still_load() {
        let stored: StoredQueuedRelayCommand = serde_json::from_value(serde_json::json!({
            "command_id": "queued-1",
            "prompt": [{"type": "text", "text": "hello"}],
            "created_at_ms": 7,
        }))
        .unwrap();
        assert!(matches!(
            stored.payload,
            StoredQueuedRelayPayload::Prompt { .. }
        ));

        let config = StoredQueuedRelayCommand {
            command_id: "queued-2".into(),
            payload: StoredQueuedRelayPayload::SetConfig {
                key: "model".into(),
                value: "sonnet".into(),
            },
            created_at_ms: 8,
        };
        let encoded = serde_json::to_value(&config).unwrap();
        assert_eq!(encoded["key"], "model");
        assert_eq!(
            serde_json::from_value::<StoredQueuedRelayCommand>(encoded).unwrap(),
            config
        );
    }

    #[test]
    fn oversized_commands_are_rejected_before_journaling() {
        let temp = tempfile::tempdir().unwrap();
        let mut relay = DurableRelay::open(temp.path(), SESSION, "1.0.0").unwrap();
        let response = relay.handle(relay_request(
            "oversized-command",
            RelayRequest::Submit {
                command_id: "oversized-command".into(),
                command: prompt(&"x".repeat(RELAY_COMMAND_BYTE_BUDGET)),
            },
        ));
        assert!(matches!(
            response.body,
            RelayResponseBody::Error {
                error: RelayProtocolError {
                    code: RelayErrorCode::InvalidRequest,
                    ..
                }
            }
        ));
        assert_eq!(relay.latest_ordinal(), 0);
    }

    #[test]
    fn truncate_start_keeps_the_tail_and_discloses_the_drop() {
        let mut short = "abcdefghij".to_owned();
        assert!(!truncate_start_with_marker(&mut short, 100));
        assert_eq!(short, "abcdefghij");

        let mut long = "abcdefghij".to_owned();
        assert!(truncate_start_with_marker(&mut long, 4));
        assert!(
            long.starts_with("[mj dropped "),
            "the drop must be disclosed: {long:?}"
        );
        assert!(long.ends_with("ghij"), "the tail must be kept: {long:?}");
    }

    #[test]
    fn oversized_observations_are_truncated_instead_of_failing() {
        let temp = tempfile::tempdir().unwrap();
        let mut relay = DurableRelay::open(temp.path(), SESSION, "1.0.0").unwrap();

        let ordinal = relay
            .record_observation(RelayObservation::Warning {
                message: "x".repeat(RELAY_EVENT_BYTE_BUDGET),
            })
            .expect("an oversized observation is recorded, not rejected");
        assert_eq!(ordinal, 1);
        assert_eq!(relay.latest_ordinal(), 1);

        let replayed = relay
            .events_after(0, crate::hel_worker::RELAY_EVENT_GENESIS_DIGEST)
            .unwrap();
        let recorded = &replayed[0];
        let RelayObservation::Warning { message } = &recorded.observation else {
            panic!(
                "expected the truncated warning, found {:?}",
                recorded.observation
            );
        };
        assert!(
            message.starts_with("xxxx"),
            "the head of the payload is kept"
        );
        assert!(message.contains("[mj truncated"), "truncation is disclosed");
        assert!(serde_json::to_vec(recorded).unwrap().len() <= RELAY_EVENT_BYTE_BUDGET);
    }

    /// The journal is append-only, so what a recorded edit costs is what it
    /// costs forever. It records the patch, not two copies of the file.
    #[test]
    fn a_recorded_edit_journals_a_patch_rather_than_the_whole_file() {
        use agent_client_protocol::schema::v1::{Diff, ToolCall, ToolCallContent};

        let temp = tempfile::tempdir().unwrap();
        let mut relay = DurableRelay::open(temp.path(), SESSION, "1.0.0").unwrap();
        let old_text = (0..4_000)
            .map(|line| format!("line {line}\n"))
            .collect::<String>();
        let new_text = old_text.replace("line 2000\n", "line 2000 edited\n");
        let mut diff = Diff::new("/repo/src/main.rs", new_text);
        diff.old_text = Some(old_text.clone());

        relay
            .record_session_update(SessionUpdate::ToolCall(
                ToolCall::new("call-1", "Edit files").content(vec![ToolCallContent::Diff(diff)]),
            ))
            .unwrap();

        let replayed = relay
            .events_after(0, crate::hel_worker::RELAY_EVENT_GENESIS_DIGEST)
            .unwrap();
        let recorded = &replayed[0];
        let RelayObservation::SessionUpdate { update } = &recorded.observation else {
            panic!(
                "expected a session update, found {:?}",
                recorded.observation
            );
        };
        let SessionUpdate::ToolCall(call) = update.as_ref() else {
            panic!("expected a tool call");
        };
        let [ToolCallContent::Diff(diff)] = call.content.as_slice() else {
            panic!("expected one diff");
        };
        assert_eq!(diff.old_text, None, "the old copy is not journalled");
        assert_eq!(diff.new_text, "", "the new copy is not journalled");
        let patch = crate::hel_diff::patch_of(diff);
        assert_eq!((patch.insertions, patch.deletions), (1, 1));
        assert!(patch.text.contains("+line 2000 edited\n"));
        assert!(
            serde_json::to_vec(recorded).unwrap().len() * 20 < old_text.len(),
            "a one-line edit still cost a copy of the file"
        );
    }

    #[test]
    fn operational_state_is_payload_free_and_bounded() {
        let temp = tempfile::tempdir().unwrap();
        let mut relay = DurableRelay::open(temp.path(), SESSION, "1.0.0").unwrap();
        submit_relay(
            &mut relay,
            "secret-prompt",
            prompt("payload-that-must-not-be-in-operational-state"),
        );
        let encoded = serde_json::to_vec(&relay.operational_state()).unwrap();
        assert!(encoded.len() <= RELAY_STATE_BYTE_BUDGET);
        let encoded = String::from_utf8(encoded).unwrap();
        assert!(encoded.contains("secret-prompt"));
        assert!(!encoded.contains("payload-that-must-not-be-in-operational-state"));

        let half_budget = RELAY_STATE_BYTE_BUDGET / 2;
        relay
            .record_observation(RelayObservation::ConfigurationUpdated {
                key: "large-one".into(),
                value: "a".repeat(half_budget),
            })
            .unwrap();
        let before = relay.latest_ordinal();
        let error = relay
            .record_observation(RelayObservation::ConfigurationUpdated {
                key: "large-two".into(),
                value: "b".repeat(half_budget),
            })
            .unwrap_err();
        assert!(error.to_string().contains("operational state is too large"));
        assert_eq!(relay.latest_ordinal(), before);
    }

    #[test]
    fn event_chain_detects_cursor_and_body_desynchronization() {
        let temp = tempfile::tempdir().unwrap();
        let mut relay = DurableRelay::open(temp.path(), SESSION, "1.0.0").unwrap();
        relay
            .record_observation(RelayObservation::Warning {
                message: "authentic".into(),
            })
            .unwrap();
        let event = retained_events(&relay)[0].clone();
        validate_relay_event(0, RELAY_EVENT_GENESIS_DIGEST, &event).unwrap();

        let mut tampered = event;
        tampered.observation = RelayObservation::Warning {
            message: "tampered".into(),
        };
        assert!(validate_relay_event(0, RELAY_EVENT_GENESIS_DIGEST, &tampered).is_err());

        let mismatch = relay.handle(relay_request(
            "attach-wrong-digest",
            RelayRequest::Attach {
                after_ordinal: 0,
                after_digest: "a".repeat(64),
            },
        ));
        assert!(matches!(
            mismatch.body,
            RelayResponseBody::Error {
                error: RelayProtocolError {
                    code: RelayErrorCode::Desynchronized,
                    ..
                }
            }
        ));
    }
}