everruns-platform 0.19.2

Backend control-plane entities and store contracts for the Everruns Platform
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
//! Session-owned managed sandbox abstractions.
//!
//! `session_sandbox` is the provider-neutral contract for "one managed sandbox
//! per session". The capability in `capabilities/session_sandbox.rs` exposes
//! generic `sandbox_*` tools, while integration crates register concrete
//! providers (Daytona first) through the inventory plugin system below.

use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use everruns_capability::CapabilityRef as AgentCapabilityConfig;
use everruns_core::tool_context::ToolContext;
use everruns_core::tools::ToolExecutionResult;
use everruns_provider::tool_types::ToolHints;

/// Capability id for the managed session sandbox capability.
pub const SESSION_SANDBOX_CAPABILITY_ID: &str = "session_sandbox";
/// Secret name used to persist the managed sandbox record for a session.
pub const SESSION_SANDBOX_SECRET_NAME: &str = "session_sandbox";
/// Default idle timeout for auto-pausing the managed sandbox.
pub const DEFAULT_SESSION_SANDBOX_IDLE_TIMEOUT_SECS: u64 = 180;

/// Session sandbox configuration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SessionSandboxConfig {
    /// Concrete provider id (e.g. `daytona`).
    pub provider: String,
    /// Start the sandbox proactively when the session is created.
    #[serde(default = "default_true")]
    pub auto_start: bool,
    /// Pause the sandbox after this much session inactivity.
    #[serde(default = "default_idle_timeout")]
    pub idle_pause_after_seconds: u64,
    /// Provider-specific extra configuration.
    #[serde(default = "default_provider_config")]
    pub provider_config: Value,
    /// Optional one-time initialization commands executed after create.
    #[serde(default)]
    pub init: SessionSandboxInitConfig,
}

impl Default for SessionSandboxConfig {
    fn default() -> Self {
        Self {
            provider: String::new(),
            auto_start: true,
            idle_pause_after_seconds: DEFAULT_SESSION_SANDBOX_IDLE_TIMEOUT_SECS,
            provider_config: default_provider_config(),
            init: SessionSandboxInitConfig::default(),
        }
    }
}

/// One-time sandbox initialization.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct SessionSandboxInitConfig {
    #[serde(default)]
    pub commands: Vec<String>,
}

/// Runtime lifecycle status of the managed sandbox.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SessionSandboxStatus {
    Running,
    Paused,
    /// The provider resource disappeared and must be replaced before use.
    Lost,
}

/// Provider-owned sandbox instance record persisted in session secrets.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SessionSandboxInstance {
    /// Provider-specific stable identifier (e.g. Daytona sandbox id).
    pub external_id: String,
    /// Optional human-readable name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    /// Optional default workspace path inside the sandbox.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace_path: Option<String>,
    /// Provider-specific non-secret payload needed for resume/ops.
    #[serde(default)]
    pub provider_state: Value,
    /// Provider-specific non-secret metadata for UI/debugging.
    #[serde(default)]
    pub metadata: Value,
}

/// Persisted managed sandbox state.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SessionSandboxState {
    pub provider: String,
    pub status: SessionSandboxStatus,
    pub instance: SessionSandboxInstance,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub init_completed_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_init_error: Option<String>,
    pub created_at: String,
    pub updated_at: String,
}

/// Provider-neutral exec request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SessionSandboxExecRequest {
    pub command: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
    #[serde(default = "default_output_mode")]
    pub output_mode: String,
}

/// Provider-neutral exec result.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SessionSandboxExecResponse {
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
    pub success: bool,
    pub truncated: bool,
    pub total_lines: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw_output: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
}

/// Provider-neutral file read result.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SessionSandboxReadFileResponse {
    pub path: String,
    pub content: String,
    pub encoding: String,
}

/// Provider-neutral file write result.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SessionSandboxWriteFileResponse {
    pub path: String,
    pub bytes_written: usize,
}

/// Provider-neutral status view.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SessionSandboxStatusResponse {
    pub provider: String,
    pub session_status: SessionSandboxStatus,
    pub external_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace_path: Option<String>,
    #[serde(default)]
    pub metadata: Value,
}

/// Provider trait implemented by integration crates.
#[async_trait::async_trait]
pub trait SessionSandboxProvider: Send + Sync {
    fn id(&self) -> &str;

    async fn create(
        &self,
        context: &ToolContext,
        config: &SessionSandboxConfig,
    ) -> Result<SessionSandboxInstance, ToolExecutionResult>;

    async fn resume(
        &self,
        context: &ToolContext,
        config: &SessionSandboxConfig,
        instance: &SessionSandboxInstance,
    ) -> Result<SessionSandboxInstance, ToolExecutionResult>;

    async fn pause(
        &self,
        context: &ToolContext,
        config: &SessionSandboxConfig,
        instance: &SessionSandboxInstance,
    ) -> Result<SessionSandboxInstance, ToolExecutionResult>;

    async fn delete(
        &self,
        context: &ToolContext,
        config: &SessionSandboxConfig,
        instance: &SessionSandboxInstance,
    ) -> Result<(), ToolExecutionResult>;

    async fn exec(
        &self,
        context: &ToolContext,
        config: &SessionSandboxConfig,
        instance: &SessionSandboxInstance,
        request: &SessionSandboxExecRequest,
    ) -> Result<SessionSandboxExecResponse, ToolExecutionResult>;

    async fn read_file(
        &self,
        context: &ToolContext,
        config: &SessionSandboxConfig,
        instance: &SessionSandboxInstance,
        path: &str,
    ) -> Result<SessionSandboxReadFileResponse, ToolExecutionResult>;

    async fn write_file(
        &self,
        context: &ToolContext,
        config: &SessionSandboxConfig,
        instance: &SessionSandboxInstance,
        path: &str,
        content: &str,
    ) -> Result<SessionSandboxWriteFileResponse, ToolExecutionResult>;

    /// Persist the current workspace after a completed mutating operation.
    /// Providers without disposable local filesystems may keep the default.
    async fn checkpoint(
        &self,
        _context: &ToolContext,
        _config: &SessionSandboxConfig,
        instance: &SessionSandboxInstance,
    ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
        Ok(instance.clone())
    }

    /// Point the provider's recovery state at `revision`, or clear it when
    /// `None`, without touching the running workspace.
    ///
    /// Reconciliation decides which revision a session may recover to from the
    /// checkpoint records; this is how that decision reaches the provider state
    /// the restore actually reads. Providers with no recovery state keep the
    /// default: there is nothing to rewind, and reconciliation is a no-op for
    /// them.
    async fn rewind_checkpoint(
        &self,
        _context: &ToolContext,
        _config: &SessionSandboxConfig,
        instance: &SessionSandboxInstance,
        _revision: Option<&str>,
    ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
        Ok(instance.clone())
    }

    async fn status(
        &self,
        context: &ToolContext,
        config: &SessionSandboxConfig,
        state: &SessionSandboxState,
    ) -> Result<SessionSandboxStatusResponse, ToolExecutionResult>;
}

/// Inventory registration point for concrete session sandbox providers.
pub struct SessionSandboxProviderPlugin {
    pub factory: fn() -> Box<dyn SessionSandboxProvider>,
}

inventory::collect!(SessionSandboxProviderPlugin);

/// Look up a registered provider by id.
pub fn create_session_sandbox_provider(
    provider_id: &str,
) -> Option<Box<dyn SessionSandboxProvider>> {
    inventory::iter::<SessionSandboxProviderPlugin>
        .into_iter()
        .map(|plugin| (plugin.factory)())
        .find(|provider| provider.id() == provider_id)
}

/// Extract the effective session sandbox config from a capability list.
pub fn session_sandbox_config_from_capabilities(
    capability_configs: &[AgentCapabilityConfig],
) -> Result<Option<SessionSandboxConfig>, String> {
    let Some(capability) = capability_configs
        .iter()
        .find(|cap| cap.capability_id() == SESSION_SANDBOX_CAPABILITY_ID)
    else {
        return Ok(None);
    };

    let config: SessionSandboxConfig = serde_json::from_value(capability.config_value().clone())
        .map_err(|e| format!("Invalid session_sandbox config: {e}"))?;

    if config.provider.trim().is_empty() {
        return Err("session_sandbox config requires non-empty 'provider'".to_string());
    }
    if config.idle_pause_after_seconds == 0 {
        return Err("session_sandbox config requires idle_pause_after_seconds >= 1".to_string());
    }

    Ok(Some(config))
}

/// Load the managed sandbox state from session secret storage.
pub async fn load_session_sandbox_state(
    context: &ToolContext,
) -> Result<Option<SessionSandboxState>, ToolExecutionResult> {
    let storage = context
        .storage_store
        .as_ref()
        .ok_or_else(|| ToolExecutionResult::tool_error("Storage not available in this context"))?;

    let Some(raw) = storage
        .get_secret(context.session_id, SESSION_SANDBOX_SECRET_NAME)
        .await
        .map_err(ToolExecutionResult::internal_error)?
    else {
        return Ok(None);
    };

    let state: SessionSandboxState = serde_json::from_str(&raw).map_err(|e| {
        ToolExecutionResult::internal_error_msg(format!("Corrupt session sandbox state: {e}"))
    })?;
    Ok(Some(state))
}

/// Persist the managed sandbox state into session secret storage.
pub async fn save_session_sandbox_state(
    context: &ToolContext,
    state: &SessionSandboxState,
) -> Result<(), ToolExecutionResult> {
    let storage = context
        .storage_store
        .as_ref()
        .ok_or_else(|| ToolExecutionResult::tool_error("Storage not available in this context"))?;

    let raw = serde_json::to_string(state).map_err(|e| {
        ToolExecutionResult::internal_error_msg(format!(
            "Failed to encode session sandbox state: {e}"
        ))
    })?;

    storage
        .set_secret(context.session_id, SESSION_SANDBOX_SECRET_NAME, &raw)
        .await
        .map_err(ToolExecutionResult::internal_error)
}

/// Delete the managed sandbox state from session secret storage.
pub async fn delete_session_sandbox_state(
    context: &ToolContext,
) -> Result<(), ToolExecutionResult> {
    let storage = context
        .storage_store
        .as_ref()
        .ok_or_else(|| ToolExecutionResult::tool_error("Storage not available in this context"))?;

    storage
        .delete_secret(context.session_id, SESSION_SANDBOX_SECRET_NAME)
        .await
        .map_err(ToolExecutionResult::internal_error)?;
    Ok(())
}

/// Start the managed sandbox when absent and resume it when paused.
pub async fn ensure_session_sandbox_running(
    context: &ToolContext,
    config: &SessionSandboxConfig,
) -> Result<SessionSandboxState, ToolExecutionResult> {
    let Some(provider) = create_session_sandbox_provider(&config.provider) else {
        return Err(ToolExecutionResult::tool_error(format!(
            "Session sandbox provider '{}' is not registered",
            config.provider
        )));
    };

    match load_session_sandbox_state(context).await? {
        Some(existing) => {
            if existing.provider != config.provider {
                return Err(ToolExecutionResult::tool_error(format!(
                    "Session sandbox provider mismatch: state has '{}', config requests '{}'",
                    existing.provider, config.provider
                )));
            }

            let mut state = existing;

            // Before anything reads the recovery pointer: a checkpoint attached
            // by a tool call that never settled must not be what this session
            // resumes onto (EVE-870).
            reconcile_session_sandbox_checkpoint(context, provider.as_ref(), config, &mut state)
                .await?;

            let needs_resume = match state.status {
                SessionSandboxStatus::Paused | SessionSandboxStatus::Lost => true,
                SessionSandboxStatus::Running => {
                    let status = provider.status(context, config, &state).await?;
                    status.session_status != SessionSandboxStatus::Running
                }
            };

            if needs_resume {
                state.instance = provider.resume(context, config, &state.instance).await?;
                state.status = SessionSandboxStatus::Running;
                state.last_init_error = None;
                state.updated_at = now_rfc3339();
                save_session_sandbox_state(context, &state).await?;
            }

            run_session_sandbox_init_if_needed(context, provider.as_ref(), config, &mut state)
                .await?;
            Ok(state)
        }
        None => {
            let instance = provider.create(context, config).await?;
            let mut state = SessionSandboxState {
                provider: config.provider.clone(),
                status: SessionSandboxStatus::Running,
                instance,
                init_completed_at: None,
                last_init_error: None,
                created_at: now_rfc3339(),
                updated_at: now_rfc3339(),
            };
            save_session_sandbox_state(context, &state).await?;
            run_session_sandbox_init_if_needed(context, provider.as_ref(), config, &mut state)
                .await?;
            Ok(state)
        }
    }
}

/// Pause the managed sandbox if it exists and is running.
pub async fn pause_session_sandbox(
    context: &ToolContext,
    config: &SessionSandboxConfig,
) -> Result<Option<SessionSandboxState>, ToolExecutionResult> {
    let Some(mut state) = load_session_sandbox_state(context).await? else {
        return Ok(None);
    };

    if state.provider != config.provider {
        return Err(ToolExecutionResult::tool_error(format!(
            "Session sandbox provider mismatch: state has '{}', config requests '{}'",
            state.provider, config.provider
        )));
    }
    if state.status == SessionSandboxStatus::Paused {
        return Ok(Some(state));
    }

    let Some(provider) = create_session_sandbox_provider(&config.provider) else {
        return Err(ToolExecutionResult::tool_error(format!(
            "Session sandbox provider '{}' is not registered",
            config.provider
        )));
    };

    state.instance = provider.pause(context, config, &state.instance).await?;
    state.status = SessionSandboxStatus::Paused;
    state.updated_at = now_rfc3339();
    save_session_sandbox_state(context, &state).await?;
    Ok(Some(state))
}

/// Delete the managed sandbox if it exists.
pub async fn delete_session_sandbox(
    context: &ToolContext,
    config: &SessionSandboxConfig,
) -> Result<bool, ToolExecutionResult> {
    let Some(state) = load_session_sandbox_state(context).await? else {
        return Ok(false);
    };

    if state.provider != config.provider {
        return Err(ToolExecutionResult::tool_error(format!(
            "Session sandbox provider mismatch: state has '{}', config requests '{}'",
            state.provider, config.provider
        )));
    }

    let Some(provider) = create_session_sandbox_provider(&config.provider) else {
        return Err(ToolExecutionResult::tool_error(format!(
            "Session sandbox provider '{}' is not registered",
            config.provider
        )));
    };

    provider.delete(context, config, &state.instance).await?;
    delete_session_sandbox_state(context).await?;
    Ok(true)
}

/// Execute one-time initialization commands when configured and not yet completed.
pub async fn run_session_sandbox_init_if_needed(
    context: &ToolContext,
    provider: &dyn SessionSandboxProvider,
    config: &SessionSandboxConfig,
    state: &mut SessionSandboxState,
) -> Result<(), ToolExecutionResult> {
    if state.init_completed_at.is_some() || config.init.commands.is_empty() {
        return Ok(());
    }

    for command in &config.init.commands {
        let response = provider
            .exec(
                context,
                config,
                &state.instance,
                &SessionSandboxExecRequest {
                    command: command.clone(),
                    cwd: state.instance.workspace_path.clone(),
                    timeout_ms: None,
                    output_mode: "concise".to_string(),
                },
            )
            .await?;

        checkpoint_session_sandbox(context, provider, config, state).await?;

        if response.exit_code != 0 {
            state.last_init_error = Some(format!(
                "Init command failed with exit code {}: {}",
                response.exit_code, command
            ));
            state.updated_at = now_rfc3339();
            save_session_sandbox_state(context, state).await?;
            return Err(ToolExecutionResult::tool_error(format!(
                "Session sandbox init failed for command '{}': {}",
                command,
                if response.stderr.is_empty() {
                    response.stdout
                } else if response.stdout.is_empty() {
                    response.stderr
                } else {
                    format!("{}\n{}", response.stdout, response.stderr)
                }
            )));
        }
    }

    state.init_completed_at = Some(now_rfc3339());
    state.last_init_error = None;
    state.updated_at = now_rfc3339();
    save_session_sandbox_state(context, state).await?;
    Ok(())
}

/// Provider-neutral key a provider sets on `SessionSandboxInstance::metadata`
/// to name the workspace revision its checkpoint produced.
const CHECKPOINT_REVISION_METADATA_KEY: &str = "checkpoint_revision";

/// Persist the provider checkpoint binding before the mutating tool result is
/// returned to the runtime.
///
/// Writes happen in this order (EVE-870):
///
/// 1. the provider uploads the archive and names a revision;
/// 2. the revision is recorded as an *unattached* checkpoint;
/// 3. the secret binding is written, which is what makes the revision
///    recoverable today;
/// 4. the checkpoint is attached, marking it authoritative.
///
/// A crash between 2 and 4 therefore leaves a checkpoint row nothing points at,
/// which garbage collection may drop, rather than an authoritative pointer to a
/// revision no committed turn produced.
pub async fn checkpoint_session_sandbox(
    context: &ToolContext,
    provider: &dyn SessionSandboxProvider,
    config: &SessionSandboxConfig,
    state: &mut SessionSandboxState,
) -> Result<(), ToolExecutionResult> {
    let checkpointed = provider
        .checkpoint(context, config, &state.instance)
        .await?;
    if checkpointed != state.instance {
        let revision = checkpointed
            .metadata
            .get(CHECKPOINT_REVISION_METADATA_KEY)
            .and_then(Value::as_str)
            .map(str::to_string);

        let recorded = match revision {
            Some(revision) => record_sandbox_checkpoint(context, config, &revision).await,
            None => None,
        };

        state.instance = checkpointed;
        state.updated_at = now_rfc3339();
        save_session_sandbox_state(context, state).await?;

        if let Some((store, sandbox, checkpoint_id)) = recorded {
            // The secret binding is still what recovery reads, so a failure to
            // attach must not fail the tool: it leaves a collectable orphan and
            // the pre-EVE-870 behaviour. This becomes fatal in the slice that
            // moves recovery onto `sandboxes.current_checkpoint_id`.
            if let Err(error) = store
                .attach_checkpoint(sandbox.id, checkpoint_id, sandbox.generation)
                .await
            {
                tracing::warn!(
                    sandbox_id = %sandbox.id,
                    %error,
                    "failed to attach sandbox checkpoint; leaving it collectable"
                );
            }
        }
    }
    Ok(())
}

/// Drop the authoritative checkpoint when the tool call it was taken for never
/// committed, and rewind the provider's recovery state to the one before it.
///
/// `checkpoint_session_sandbox` attaches a checkpoint before the runtime settles
/// the tool result it belongs to. A control-plane crash in that window leaves
/// the workspace one revision ahead of the conversation: the agent resumes with
/// no record of the command, re-runs it, and finds a workspace the first attempt
/// already mutated. This runs on resume and puts the two back in step.
///
/// Deliberately conservative. It only ever rejects the *current* checkpoint, and
/// only when durable storage positively says the source call is not settled.
/// Anything it cannot establish — no store installed, no source call recorded,
/// a stale generation — leaves the pointer alone, because the failure mode of
/// over-eager rollback is discarding real work.
async fn reconcile_session_sandbox_checkpoint(
    context: &ToolContext,
    provider: &dyn SessionSandboxProvider,
    config: &SessionSandboxConfig,
    state: &mut SessionSandboxState,
) -> Result<(), ToolExecutionResult> {
    use crate::sandbox_checkpoint::{DurableToolResultStoreExt, SandboxCheckpointStoreExt};
    use everruns_core::durability::DurableToolCallStatus;

    // Both halves are needed to decide anything. Hosts that install neither
    // (remote workers, embedded Framework hosts) keep the pre-EVE-870 behaviour.
    let Some(checkpoints) = context.extensions.get::<SandboxCheckpointStoreExt>() else {
        return Ok(());
    };
    let Some(durable) = context.extensions.get::<DurableToolResultStoreExt>() else {
        return Ok(());
    };
    let (checkpoints, durable) = (checkpoints.0.clone(), durable.0.clone());

    let sandbox = match checkpoints
        .ensure_sandbox(context.session_id, &config.provider)
        .await
    {
        Ok(sandbox) => sandbox,
        Err(error) => {
            tracing::warn!(%error, "failed to resolve logical sandbox; skipping reconciliation");
            return Ok(());
        }
    };

    let head = match checkpoints.current_checkpoint(sandbox.id).await {
        Ok(Some(head)) => head,
        Ok(None) => return Ok(()),
        Err(error) => {
            tracing::warn!(%error, "failed to read current checkpoint; skipping reconciliation");
            return Ok(());
        }
    };

    // A checkpoint with no source call was not taken for a tool result, so there
    // is nothing to compare it against and no reason to distrust it.
    let (Some(turn_id), Some(tool_call_id)) = (
        head.source_turn_id.as_deref(),
        head.source_tool_call_id.as_deref(),
    ) else {
        return Ok(());
    };

    let status = match durable.get_tool_call_status(turn_id, tool_call_id).await {
        Ok(status) => status,
        Err(error) => {
            tracing::warn!(%error, "failed to read durable tool call status; skipping reconciliation");
            return Ok(());
        }
    };

    // `Settled` is the only state that means "the conversation records a result
    // for this revision". `Interrupted` records that the call did *not* produce
    // one, and the transcript's interrupted placeholder invites the agent to
    // retry — against the workspace as it was before, which is the whole point.
    if matches!(status, Some(DurableToolCallStatus::Settled { .. })) {
        return Ok(());
    }

    let restored = match checkpoints
        .rollback_current_checkpoint(sandbox.id, head.id, sandbox.generation)
        .await
    {
        Ok(restored) => restored,
        Err(error) => {
            tracing::warn!(
                sandbox_id = %sandbox.id,
                %error,
                "failed to roll back uncommitted sandbox checkpoint"
            );
            return Ok(());
        }
    };

    tracing::info!(
        sandbox_id = %sandbox.id,
        rejected_revision = %head.workspace_revision,
        restored_revision = restored.as_ref().map(|c| c.workspace_revision.as_str()).unwrap_or("<none>"),
        "rolled sandbox back to its last committed checkpoint"
    );

    let rewound = provider
        .rewind_checkpoint(
            context,
            config,
            &state.instance,
            restored.as_ref().map(|c| c.workspace_revision.as_str()),
        )
        .await?;
    if rewound != state.instance {
        state.instance = rewound;
        state.updated_at = now_rfc3339();
        save_session_sandbox_state(context, state).await?;
    }

    Ok(())
}

/// Record an uploaded revision as an unattached checkpoint.
///
/// Returns the store, sandbox and checkpoint id so the caller can attach it
/// once the pointer write has succeeded. Hosts without the store installed
/// (remote workers, embedded Framework hosts) get `None` and keep the
/// secret-only behaviour.
async fn record_sandbox_checkpoint(
    context: &ToolContext,
    config: &SessionSandboxConfig,
    revision: &str,
) -> Option<(
    std::sync::Arc<dyn crate::sandbox_checkpoint::SandboxCheckpointStore>,
    crate::sandbox_checkpoint::SandboxRef,
    uuid::Uuid,
)> {
    use crate::sandbox_checkpoint::{
        NewSandboxCheckpoint, SandboxCheckpointKind, SandboxCheckpointStoreExt,
    };

    let store = context
        .extensions
        .get::<SandboxCheckpointStoreExt>()?
        .0
        .clone();

    let sandbox = match store
        .ensure_sandbox(context.session_id, &config.provider)
        .await
    {
        Ok(sandbox) => sandbox,
        Err(error) => {
            tracing::warn!(%error, "failed to resolve logical sandbox; skipping checkpoint record");
            return None;
        }
    };

    let checkpoint = match store
        .record_checkpoint(NewSandboxCheckpoint {
            sandbox_id: sandbox.id,
            generation: sandbox.generation,
            source_turn_id: context
                .event_context
                .as_ref()
                .and_then(|events| events.turn_id.as_ref())
                .map(ToString::to_string),
            source_tool_call_id: context.tool_call_id.clone(),
            kind: SandboxCheckpointKind::PortableWorkspace,
            provider_ref: None,
            workspace_revision: revision.to_string(),
        })
        .await
    {
        Ok(checkpoint) => checkpoint,
        Err(error) => {
            tracing::warn!(%error, "failed to record sandbox checkpoint");
            return None;
        }
    };

    Some((store, sandbox, checkpoint.id))
}

/// Shared hints for stateful remote sandbox tools.
pub fn session_sandbox_tool_hints() -> ToolHints {
    ToolHints::default()
        .with_concurrency_class("session_sandbox")
        .with_open_world(true)
        .with_requires_secrets(true)
        .with_long_running(true)
}

fn default_true() -> bool {
    true
}

fn default_idle_timeout() -> u64 {
    DEFAULT_SESSION_SANDBOX_IDLE_TIMEOUT_SECS
}

fn default_provider_config() -> Value {
    json!({})
}

fn default_output_mode() -> String {
    // EVE-489: persistence-first default for exec-style sandbox tools.
    "auto".to_string()
}

fn now_rfc3339() -> String {
    Utc::now().to_rfc3339()
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use chrono::Utc;
    use everruns_core::{session_services::SecretInfo, session_services::SessionStorageStore};
    use std::collections::HashMap;
    use std::sync::{Arc, LazyLock, Mutex};

    // `everruns-host` reserves this name from the user-facing secret_store, but
    // it cannot name the constant: host is a dependency of this crate, not the
    // other way round. Pin the two together here, where the constant is
    // defined, so a rename cannot quietly reopen the write path that lets a
    // session point Daytona recovery at another session's state.
    #[test]
    fn the_sandbox_secret_name_is_reserved_from_session_storage() {
        assert!(crate::capabilities::is_internal_session_secret_name(
            SESSION_SANDBOX_SECRET_NAME
        ));
    }

    #[derive(Clone, Default)]
    struct MemorySecrets {
        secrets: Arc<Mutex<HashMap<String, String>>>,
    }

    #[async_trait]
    impl SessionStorageStore for MemorySecrets {
        async fn set_value(
            &self,
            _session_id: everruns_provider::typed_id::SessionId,
            _key: &str,
            _value: &str,
        ) -> everruns_provider::error::Result<()> {
            unreachable!()
        }

        async fn get_value(
            &self,
            _session_id: everruns_provider::typed_id::SessionId,
            _key: &str,
        ) -> everruns_provider::error::Result<Option<String>> {
            unreachable!()
        }

        async fn delete_value(
            &self,
            _session_id: everruns_provider::typed_id::SessionId,
            _key: &str,
        ) -> everruns_provider::error::Result<bool> {
            unreachable!()
        }

        async fn list_keys(
            &self,
            _session_id: everruns_provider::typed_id::SessionId,
        ) -> everruns_provider::error::Result<Vec<everruns_core::session_services::KeyInfo>>
        {
            unreachable!()
        }

        async fn set_secret(
            &self,
            _session_id: everruns_provider::typed_id::SessionId,
            name: &str,
            value: &str,
        ) -> everruns_provider::error::Result<()> {
            self.secrets
                .lock()
                .unwrap()
                .insert(name.to_string(), value.to_string());
            Ok(())
        }

        async fn get_secret(
            &self,
            _session_id: everruns_provider::typed_id::SessionId,
            name: &str,
        ) -> everruns_provider::error::Result<Option<String>> {
            Ok(self.secrets.lock().unwrap().get(name).cloned())
        }

        async fn delete_secret(
            &self,
            _session_id: everruns_provider::typed_id::SessionId,
            name: &str,
        ) -> everruns_provider::error::Result<bool> {
            Ok(self.secrets.lock().unwrap().remove(name).is_some())
        }

        async fn list_secrets(
            &self,
            _session_id: everruns_provider::typed_id::SessionId,
        ) -> everruns_provider::error::Result<Vec<SecretInfo>> {
            Ok(self
                .secrets
                .lock()
                .unwrap()
                .keys()
                .map(|name| SecretInfo {
                    name: name.clone(),
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                })
                .collect())
        }
    }

    #[test]
    fn extracts_valid_session_sandbox_config() {
        let config =
            session_sandbox_config_from_capabilities(&[AgentCapabilityConfig::with_config(
                SESSION_SANDBOX_CAPABILITY_ID,
                serde_json::json!({
                    "provider": "daytona",
                    "auto_start": false,
                    "idle_pause_after_seconds": 90,
                    "init": { "commands": ["echo ready"] }
                }),
            )])
            .unwrap()
            .unwrap();

        assert_eq!(config.provider, "daytona");
        assert!(!config.auto_start);
        assert_eq!(config.idle_pause_after_seconds, 90);
        assert_eq!(config.provider_config, json!({}));
        assert_eq!(config.init.commands, vec!["echo ready"]);
    }

    #[test]
    fn rejects_missing_provider() {
        let err = session_sandbox_config_from_capabilities(&[AgentCapabilityConfig::with_config(
            SESSION_SANDBOX_CAPABILITY_ID,
            serde_json::json!({ "auto_start": true }),
        )])
        .unwrap_err();

        assert!(err.contains("provider"));
    }

    #[tokio::test]
    async fn session_sandbox_state_round_trip() {
        let storage = Arc::new(MemorySecrets::default());
        let context =
            ToolContext::with_storage_store(everruns_provider::typed_id::SessionId::new(), storage);

        let state = SessionSandboxState {
            provider: "daytona".to_string(),
            status: SessionSandboxStatus::Running,
            instance: SessionSandboxInstance {
                external_id: "sb_test".to_string(),
                display_name: Some("Sandbox".to_string()),
                workspace_path: Some("/home/daytona".to_string()),
                provider_state: serde_json::json!({"sandbox_id":"sb_test"}),
                metadata: serde_json::json!({"state":"started"}),
            },
            init_completed_at: Some(now_rfc3339()),
            last_init_error: None,
            created_at: now_rfc3339(),
            updated_at: now_rfc3339(),
        };

        save_session_sandbox_state(&context, &state).await.unwrap();
        let loaded = load_session_sandbox_state(&context).await.unwrap().unwrap();
        assert_eq!(loaded.provider, "daytona");
        assert_eq!(loaded.instance.external_id, "sb_test");
        assert_eq!(loaded.status, SessionSandboxStatus::Running);
    }

    #[derive(Clone)]
    struct TestProviderSandboxState {
        remote_status: SessionSandboxStatus,
        resume_calls: usize,
        exec_commands: Vec<String>,
    }

    #[derive(Default)]
    struct TestProviderState {
        sandboxes: HashMap<String, TestProviderSandboxState>,
    }

    static TEST_PROVIDER_STATE: LazyLock<Mutex<TestProviderState>> =
        LazyLock::new(|| Mutex::new(TestProviderState::default()));

    fn sandbox_state_mut<'a>(
        state: &'a mut TestProviderState,
        external_id: &str,
    ) -> &'a mut TestProviderSandboxState {
        state
            .sandboxes
            .entry(external_id.to_string())
            .or_insert_with(|| TestProviderSandboxState {
                remote_status: SessionSandboxStatus::Running,
                resume_calls: 0,
                exec_commands: Vec::new(),
            })
    }

    fn test_provider_state(external_id: &str) -> TestProviderSandboxState {
        TEST_PROVIDER_STATE
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .sandboxes
            .get(external_id)
            .cloned()
            .unwrap_or(TestProviderSandboxState {
                remote_status: SessionSandboxStatus::Running,
                resume_calls: 0,
                exec_commands: Vec::new(),
            })
    }

    fn reset_test_provider_state(external_id: &str, remote_status: SessionSandboxStatus) {
        let mut state = TEST_PROVIDER_STATE
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        state.sandboxes.insert(
            external_id.to_string(),
            TestProviderSandboxState {
                remote_status,
                resume_calls: 0,
                exec_commands: Vec::new(),
            },
        );
    }

    struct CoreTestSessionSandboxProvider;

    inventory::submit! {
        SessionSandboxProviderPlugin {
            factory: || Box::new(CoreTestSessionSandboxProvider),
        }
    }

    #[async_trait]
    impl SessionSandboxProvider for CoreTestSessionSandboxProvider {
        fn id(&self) -> &str {
            "core-test-session-sandbox"
        }

        async fn create(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
        ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
            let instance = test_instance("sb_created");
            let mut state = TEST_PROVIDER_STATE
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            sandbox_state_mut(&mut state, &instance.external_id).remote_status =
                SessionSandboxStatus::Running;
            Ok(instance)
        }

        async fn resume(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            instance: &SessionSandboxInstance,
        ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
            let mut state = TEST_PROVIDER_STATE
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            let sandbox_state = sandbox_state_mut(&mut state, &instance.external_id);
            sandbox_state.resume_calls += 1;
            sandbox_state.remote_status = SessionSandboxStatus::Running;

            let mut resumed = instance.clone();
            resumed.metadata = json!({ "resumed": true });
            Ok(resumed)
        }

        async fn pause(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            instance: &SessionSandboxInstance,
        ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
            Ok(instance.clone())
        }

        async fn delete(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
        ) -> Result<(), ToolExecutionResult> {
            Ok(())
        }

        async fn exec(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
            request: &SessionSandboxExecRequest,
        ) -> Result<SessionSandboxExecResponse, ToolExecutionResult> {
            let mut state = TEST_PROVIDER_STATE
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            sandbox_state_mut(&mut state, &_instance.external_id)
                .exec_commands
                .push(request.command.clone());

            Ok(SessionSandboxExecResponse {
                exit_code: 0,
                stdout: "ok".to_string(),
                stderr: String::new(),
                success: true,
                truncated: false,
                total_lines: 1,
                raw_output: Some("ok".to_string()),
                hint: None,
            })
        }

        async fn read_file(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
            path: &str,
        ) -> Result<SessionSandboxReadFileResponse, ToolExecutionResult> {
            Ok(SessionSandboxReadFileResponse {
                path: path.to_string(),
                content: "data".to_string(),
                encoding: "text".to_string(),
            })
        }

        async fn write_file(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
            path: &str,
            content: &str,
        ) -> Result<SessionSandboxWriteFileResponse, ToolExecutionResult> {
            Ok(SessionSandboxWriteFileResponse {
                path: path.to_string(),
                bytes_written: content.len(),
            })
        }

        async fn status(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            state: &SessionSandboxState,
        ) -> Result<SessionSandboxStatusResponse, ToolExecutionResult> {
            let provider_state = test_provider_state(&state.instance.external_id);

            Ok(SessionSandboxStatusResponse {
                provider: state.provider.clone(),
                session_status: provider_state.remote_status,
                external_id: state.instance.external_id.clone(),
                display_name: state.instance.display_name.clone(),
                workspace_path: state.instance.workspace_path.clone(),
                metadata: json!({ "remote_status": provider_state.remote_status }),
            })
        }
    }

    fn test_instance(external_id: &str) -> SessionSandboxInstance {
        SessionSandboxInstance {
            external_id: external_id.to_string(),
            display_name: Some("Core Test Sandbox".to_string()),
            workspace_path: Some("/workspace".to_string()),
            provider_state: json!({}),
            metadata: json!({}),
        }
    }

    fn test_config_with_init(commands: Vec<&str>) -> SessionSandboxConfig {
        SessionSandboxConfig {
            provider: "core-test-session-sandbox".to_string(),
            auto_start: true,
            idle_pause_after_seconds: 180,
            provider_config: json!({}),
            init: SessionSandboxInitConfig {
                commands: commands.into_iter().map(ToString::to_string).collect(),
            },
        }
    }

    #[tokio::test]
    async fn ensure_running_resumes_when_remote_status_drifted_to_paused() {
        let external_id = "sb_drifted";
        reset_test_provider_state(external_id, SessionSandboxStatus::Paused);

        let storage = Arc::new(MemorySecrets::default());
        let context =
            ToolContext::with_storage_store(everruns_provider::typed_id::SessionId::new(), storage);
        let state = SessionSandboxState {
            provider: "core-test-session-sandbox".to_string(),
            status: SessionSandboxStatus::Running,
            instance: test_instance(external_id),
            init_completed_at: Some(now_rfc3339()),
            last_init_error: None,
            created_at: now_rfc3339(),
            updated_at: now_rfc3339(),
        };
        save_session_sandbox_state(&context, &state).await.unwrap();

        let resolved = ensure_session_sandbox_running(&context, &test_config_with_init(vec![]))
            .await
            .unwrap();

        let provider_state = test_provider_state(external_id);
        assert_eq!(provider_state.resume_calls, 1);
        assert_eq!(resolved.status, SessionSandboxStatus::Running);
        assert_eq!(resolved.instance.metadata, json!({ "resumed": true }));
    }

    #[tokio::test]
    async fn ensure_running_replaces_provider_instance_when_remote_status_is_lost() {
        let external_id = "sb_lost";
        reset_test_provider_state(external_id, SessionSandboxStatus::Lost);

        let storage = Arc::new(MemorySecrets::default());
        let context =
            ToolContext::with_storage_store(everruns_provider::typed_id::SessionId::new(), storage);
        let state = SessionSandboxState {
            provider: "core-test-session-sandbox".to_string(),
            status: SessionSandboxStatus::Running,
            instance: test_instance(external_id),
            init_completed_at: Some(now_rfc3339()),
            last_init_error: None,
            created_at: now_rfc3339(),
            updated_at: now_rfc3339(),
        };
        save_session_sandbox_state(&context, &state).await.unwrap();

        let resolved = ensure_session_sandbox_running(&context, &test_config_with_init(vec![]))
            .await
            .unwrap();

        let provider_state = test_provider_state(external_id);
        assert_eq!(provider_state.resume_calls, 1);
        assert_eq!(resolved.status, SessionSandboxStatus::Running);
        assert_eq!(resolved.instance.metadata, json!({ "resumed": true }));
    }

    #[tokio::test]
    async fn ensure_running_retries_init_when_state_is_running_but_init_unfinished() {
        let external_id = "sb_init_retry";
        reset_test_provider_state(external_id, SessionSandboxStatus::Running);

        let storage = Arc::new(MemorySecrets::default());
        let context =
            ToolContext::with_storage_store(everruns_provider::typed_id::SessionId::new(), storage);
        let state = SessionSandboxState {
            provider: "core-test-session-sandbox".to_string(),
            status: SessionSandboxStatus::Running,
            instance: test_instance(external_id),
            init_completed_at: None,
            last_init_error: Some("previous failure".to_string()),
            created_at: now_rfc3339(),
            updated_at: now_rfc3339(),
        };
        save_session_sandbox_state(&context, &state).await.unwrap();

        let resolved =
            ensure_session_sandbox_running(&context, &test_config_with_init(vec!["echo ready"]))
                .await
                .unwrap();

        let provider_state = test_provider_state(external_id);
        assert_eq!(provider_state.exec_commands, vec!["echo ready"]);
        assert!(resolved.init_completed_at.is_some());
        assert_eq!(resolved.last_init_error, None);
    }

    // EVE-870: the checkpoint record/attach ordering around the secret write.

    /// Records every store call in order so tests can assert the sequence, not
    /// just the end state — the ordering is the property that makes a crash
    /// leave a collectable orphan instead of an uncommitted pointer.
    #[derive(Clone, Default)]
    struct RecordingCheckpointStore {
        calls: Arc<Mutex<Vec<String>>>,
        fail_attach: bool,
    }

    #[async_trait]
    impl crate::sandbox_checkpoint::SandboxCheckpointStore for RecordingCheckpointStore {
        async fn ensure_sandbox(
            &self,
            _session_id: everruns_provider::typed_id::SessionId,
            provider: &str,
        ) -> Result<
            crate::sandbox_checkpoint::SandboxRef,
            crate::sandbox_checkpoint::SandboxCheckpointError,
        > {
            self.calls
                .lock()
                .unwrap()
                .push(format!("ensure_sandbox:{provider}"));
            Ok(crate::sandbox_checkpoint::SandboxRef {
                id: uuid::Uuid::nil(),
                generation: 7,
            })
        }

        async fn record_checkpoint(
            &self,
            checkpoint: crate::sandbox_checkpoint::NewSandboxCheckpoint,
        ) -> Result<
            crate::sandbox_checkpoint::SandboxCheckpoint,
            crate::sandbox_checkpoint::SandboxCheckpointError,
        > {
            self.calls.lock().unwrap().push(format!(
                "record:{}:gen{}",
                checkpoint.workspace_revision, checkpoint.generation
            ));
            Ok(crate::sandbox_checkpoint::SandboxCheckpoint {
                id: uuid::Uuid::nil(),
                sandbox_id: checkpoint.sandbox_id,
                generation: checkpoint.generation,
                source_turn_id: checkpoint.source_turn_id,
                source_tool_call_id: checkpoint.source_tool_call_id,
                kind: checkpoint.kind,
                provider_ref: checkpoint.provider_ref,
                workspace_revision: checkpoint.workspace_revision,
                attached_at: None,
                created_at: Utc::now(),
            })
        }

        async fn attach_checkpoint(
            &self,
            sandbox_id: uuid::Uuid,
            _checkpoint_id: uuid::Uuid,
            generation: i64,
        ) -> Result<(), crate::sandbox_checkpoint::SandboxCheckpointError> {
            self.calls
                .lock()
                .unwrap()
                .push(format!("attach:gen{generation}"));
            if self.fail_attach {
                return Err(
                    crate::sandbox_checkpoint::SandboxCheckpointError::StaleGeneration {
                        sandbox_id,
                        current: generation + 1,
                        carried: generation,
                    },
                );
            }
            Ok(())
        }

        async fn current_checkpoint(
            &self,
            _sandbox_id: uuid::Uuid,
        ) -> Result<
            Option<crate::sandbox_checkpoint::SandboxCheckpoint>,
            crate::sandbox_checkpoint::SandboxCheckpointError,
        > {
            Ok(None)
        }

        async fn rollback_current_checkpoint(
            &self,
            _sandbox_id: uuid::Uuid,
            _checkpoint_id: uuid::Uuid,
            _generation: i64,
        ) -> Result<
            Option<crate::sandbox_checkpoint::SandboxCheckpoint>,
            crate::sandbox_checkpoint::SandboxCheckpointError,
        > {
            unreachable!("checkpoint tests never reconcile")
        }

        async fn collect_unattached_checkpoints(
            &self,
            _sandbox_id: uuid::Uuid,
            _before: chrono::DateTime<Utc>,
            _limit: i64,
        ) -> Result<Vec<String>, crate::sandbox_checkpoint::SandboxCheckpointError> {
            Ok(Vec::new())
        }
    }

    /// Provider whose checkpoint names a new revision on the neutral
    /// `metadata.checkpoint_revision` key, the way the Daytona provider does.
    struct RevisionCheckpointProvider;

    #[async_trait]
    impl SessionSandboxProvider for RevisionCheckpointProvider {
        fn id(&self) -> &str {
            "revision-test-session-sandbox"
        }

        async fn create(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
        ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
            unreachable!()
        }

        async fn resume(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
        ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
            unreachable!()
        }

        async fn pause(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
        ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
            unreachable!()
        }

        async fn delete(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
        ) -> Result<(), ToolExecutionResult> {
            unreachable!()
        }

        async fn checkpoint(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            instance: &SessionSandboxInstance,
        ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
            let mut checkpointed = instance.clone();
            checkpointed.metadata["checkpoint_revision"] = json!("rev-42");
            Ok(checkpointed)
        }

        async fn exec(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
            _request: &SessionSandboxExecRequest,
        ) -> Result<SessionSandboxExecResponse, ToolExecutionResult> {
            unreachable!()
        }

        async fn read_file(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
            _path: &str,
        ) -> Result<SessionSandboxReadFileResponse, ToolExecutionResult> {
            unreachable!()
        }

        async fn write_file(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
            _path: &str,
            _content: &str,
        ) -> Result<SessionSandboxWriteFileResponse, ToolExecutionResult> {
            unreachable!()
        }

        async fn status(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _state: &SessionSandboxState,
        ) -> Result<SessionSandboxStatusResponse, ToolExecutionResult> {
            unreachable!()
        }
    }

    fn revision_test_state() -> SessionSandboxState {
        SessionSandboxState {
            provider: "revision-test-session-sandbox".to_string(),
            status: SessionSandboxStatus::Running,
            instance: test_instance("sb_revision"),
            init_completed_at: Some(now_rfc3339()),
            last_init_error: None,
            created_at: now_rfc3339(),
            updated_at: now_rfc3339(),
        }
    }

    fn revision_test_config() -> SessionSandboxConfig {
        SessionSandboxConfig {
            provider: "revision-test-session-sandbox".to_string(),
            auto_start: true,
            idle_pause_after_seconds: 180,
            provider_config: json!({}),
            init: SessionSandboxInitConfig { commands: vec![] },
        }
    }

    #[tokio::test]
    async fn checkpoint_records_revision_before_attaching_it() {
        let storage = Arc::new(MemorySecrets::default());
        let store = Arc::new(RecordingCheckpointStore::default());
        let context =
            ToolContext::with_storage_store(everruns_provider::typed_id::SessionId::new(), storage)
                .with_extension(Arc::new(
                    crate::sandbox_checkpoint::SandboxCheckpointStoreExt(store.clone()),
                ));

        let mut state = revision_test_state();
        checkpoint_session_sandbox(
            &context,
            &RevisionCheckpointProvider,
            &revision_test_config(),
            &mut state,
        )
        .await
        .expect("checkpoint succeeds");

        // Recording precedes attaching: a crash in between leaves an orphan
        // rather than a pointer to an uncommitted revision. The attach carries
        // the generation the upload was issued against, so a sandbox replaced
        // mid-flight rejects it.
        assert_eq!(
            store.calls.lock().unwrap().as_slice(),
            [
                "ensure_sandbox:revision-test-session-sandbox",
                "record:rev-42:gen7",
                "attach:gen7",
            ]
        );
        assert_eq!(
            state.instance.metadata["checkpoint_revision"],
            json!("rev-42")
        );
    }

    #[tokio::test]
    async fn checkpoint_persists_binding_when_no_checkpoint_store_is_installed() {
        // Remote workers and embedded Framework hosts have no store; they must
        // keep the pre-EVE-870 secret-only behaviour rather than fail the tool.
        let storage = Arc::new(MemorySecrets::default());
        let context = ToolContext::with_storage_store(
            everruns_provider::typed_id::SessionId::new(),
            storage.clone(),
        );

        let mut state = revision_test_state();
        checkpoint_session_sandbox(
            &context,
            &RevisionCheckpointProvider,
            &revision_test_config(),
            &mut state,
        )
        .await
        .expect("checkpoint succeeds without a checkpoint store");

        assert!(
            storage
                .secrets
                .lock()
                .unwrap()
                .contains_key(SESSION_SANDBOX_SECRET_NAME)
        );
    }

    #[tokio::test]
    async fn checkpoint_tolerates_a_rejected_attach() {
        // The secret binding is still what recovery reads in this slice, so a
        // fenced-out attach must leave a collectable orphan, not fail the tool.
        let storage = Arc::new(MemorySecrets::default());
        let store = Arc::new(RecordingCheckpointStore {
            calls: Arc::new(Mutex::new(Vec::new())),
            fail_attach: true,
        });
        let context = ToolContext::with_storage_store(
            everruns_provider::typed_id::SessionId::new(),
            storage.clone(),
        )
        .with_extension(Arc::new(
            crate::sandbox_checkpoint::SandboxCheckpointStoreExt(store.clone()),
        ));

        let mut state = revision_test_state();
        checkpoint_session_sandbox(
            &context,
            &RevisionCheckpointProvider,
            &revision_test_config(),
            &mut state,
        )
        .await
        .expect("a rejected attach does not fail the tool");

        assert!(
            storage
                .secrets
                .lock()
                .unwrap()
                .contains_key(SESSION_SANDBOX_SECRET_NAME)
        );
    }

    // ---- Resume-time reconciliation (EVE-870) ----

    /// Store seeded with one authoritative checkpoint, recording what
    /// reconciliation asks of it.
    struct ReconcileStore {
        head: Option<crate::sandbox_checkpoint::SandboxCheckpoint>,
        restored: Option<crate::sandbox_checkpoint::SandboxCheckpoint>,
        rollbacks: Arc<Mutex<Vec<(uuid::Uuid, i64)>>>,
    }

    fn checkpoint_row(
        revision: &str,
        source: Option<(&str, &str)>,
    ) -> crate::sandbox_checkpoint::SandboxCheckpoint {
        crate::sandbox_checkpoint::SandboxCheckpoint {
            id: uuid::Uuid::new_v4(),
            sandbox_id: uuid::Uuid::nil(),
            generation: 7,
            source_turn_id: source.map(|(turn, _)| turn.to_string()),
            source_tool_call_id: source.map(|(_, call)| call.to_string()),
            kind: crate::sandbox_checkpoint::SandboxCheckpointKind::PortableWorkspace,
            provider_ref: None,
            workspace_revision: revision.to_string(),
            attached_at: Some(Utc::now()),
            created_at: Utc::now(),
        }
    }

    #[async_trait]
    impl crate::sandbox_checkpoint::SandboxCheckpointStore for ReconcileStore {
        async fn ensure_sandbox(
            &self,
            _session_id: everruns_provider::typed_id::SessionId,
            _provider: &str,
        ) -> Result<
            crate::sandbox_checkpoint::SandboxRef,
            crate::sandbox_checkpoint::SandboxCheckpointError,
        > {
            Ok(crate::sandbox_checkpoint::SandboxRef {
                id: uuid::Uuid::nil(),
                generation: 7,
            })
        }

        async fn record_checkpoint(
            &self,
            _checkpoint: crate::sandbox_checkpoint::NewSandboxCheckpoint,
        ) -> Result<
            crate::sandbox_checkpoint::SandboxCheckpoint,
            crate::sandbox_checkpoint::SandboxCheckpointError,
        > {
            unreachable!("reconciliation never records")
        }

        async fn attach_checkpoint(
            &self,
            _sandbox_id: uuid::Uuid,
            _checkpoint_id: uuid::Uuid,
            _generation: i64,
        ) -> Result<(), crate::sandbox_checkpoint::SandboxCheckpointError> {
            unreachable!("reconciliation never attaches")
        }

        async fn current_checkpoint(
            &self,
            _sandbox_id: uuid::Uuid,
        ) -> Result<
            Option<crate::sandbox_checkpoint::SandboxCheckpoint>,
            crate::sandbox_checkpoint::SandboxCheckpointError,
        > {
            Ok(self.head.clone())
        }

        async fn rollback_current_checkpoint(
            &self,
            _sandbox_id: uuid::Uuid,
            checkpoint_id: uuid::Uuid,
            generation: i64,
        ) -> Result<
            Option<crate::sandbox_checkpoint::SandboxCheckpoint>,
            crate::sandbox_checkpoint::SandboxCheckpointError,
        > {
            self.rollbacks
                .lock()
                .unwrap()
                .push((checkpoint_id, generation));
            Ok(self.restored.clone())
        }

        async fn collect_unattached_checkpoints(
            &self,
            _sandbox_id: uuid::Uuid,
            _before: chrono::DateTime<Utc>,
            _limit: i64,
        ) -> Result<Vec<String>, crate::sandbox_checkpoint::SandboxCheckpointError> {
            Ok(Vec::new())
        }
    }

    struct FixedDurableStore(Option<everruns_core::durability::DurableToolCallStatus>);

    #[async_trait]
    impl everruns_core::durability::DurableToolResultStore for FixedDurableStore {
        async fn try_claim_tool_call(
            &self,
            _turn_id: &str,
            _tool_call_id: &str,
            _tool_name: &str,
            _args_fingerprint: &str,
        ) -> everruns_provider::error::Result<everruns_core::durability::ToolCallClaimResult>
        {
            unreachable!("reconciliation only reads")
        }

        async fn settle_tool_call(
            &self,
            _turn_id: &str,
            _tool_call_id: &str,
            _result_json: serde_json::Value,
            _status: &str,
            _claim_token: uuid::Uuid,
        ) -> everruns_provider::error::Result<bool> {
            unreachable!("reconciliation only reads")
        }

        async fn get_tool_call_status(
            &self,
            _turn_id: &str,
            _tool_call_id: &str,
        ) -> everruns_provider::error::Result<
            Option<everruns_core::durability::DurableToolCallStatus>,
        > {
            Ok(self.0.clone())
        }
    }

    /// Provider that records every rewind and applies it to `provider_state`,
    /// the way the Daytona provider rewrites its recovery binding.
    struct RewindProvider {
        rewinds: Arc<Mutex<Vec<Option<String>>>>,
    }

    #[async_trait]
    impl SessionSandboxProvider for RewindProvider {
        fn id(&self) -> &str {
            "rewind-test-session-sandbox"
        }

        async fn create(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
        ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
            unreachable!()
        }

        async fn resume(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            instance: &SessionSandboxInstance,
        ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
            Ok(instance.clone())
        }

        async fn pause(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            instance: &SessionSandboxInstance,
        ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
            Ok(instance.clone())
        }

        async fn delete(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
        ) -> Result<(), ToolExecutionResult> {
            Ok(())
        }

        async fn exec(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
            _request: &SessionSandboxExecRequest,
        ) -> Result<SessionSandboxExecResponse, ToolExecutionResult> {
            unreachable!()
        }

        async fn read_file(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
            _path: &str,
        ) -> Result<SessionSandboxReadFileResponse, ToolExecutionResult> {
            unreachable!()
        }

        async fn write_file(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            _instance: &SessionSandboxInstance,
            _path: &str,
            _content: &str,
        ) -> Result<SessionSandboxWriteFileResponse, ToolExecutionResult> {
            unreachable!()
        }

        async fn rewind_checkpoint(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            instance: &SessionSandboxInstance,
            revision: Option<&str>,
        ) -> Result<SessionSandboxInstance, ToolExecutionResult> {
            self.rewinds
                .lock()
                .unwrap()
                .push(revision.map(ToString::to_string));
            let mut rewound = instance.clone();
            rewound.provider_state["recovery"] = json!({ "head_revision": revision });
            Ok(rewound)
        }

        async fn status(
            &self,
            _context: &ToolContext,
            _config: &SessionSandboxConfig,
            state: &SessionSandboxState,
        ) -> Result<SessionSandboxStatusResponse, ToolExecutionResult> {
            Ok(SessionSandboxStatusResponse {
                provider: state.provider.clone(),
                session_status: SessionSandboxStatus::Running,
                external_id: state.instance.external_id.clone(),
                display_name: None,
                workspace_path: None,
                metadata: json!({}),
            })
        }
    }

    struct ReconcileHarness {
        context: ToolContext,
        state: SessionSandboxState,
        rollbacks: Arc<Mutex<Vec<(uuid::Uuid, i64)>>>,
        rewinds: Arc<Mutex<Vec<Option<String>>>>,
        provider: RewindProvider,
    }

    fn reconcile_harness(
        head: Option<crate::sandbox_checkpoint::SandboxCheckpoint>,
        restored: Option<crate::sandbox_checkpoint::SandboxCheckpoint>,
        durable: Option<everruns_core::durability::DurableToolCallStatus>,
        install_durable_ext: bool,
    ) -> ReconcileHarness {
        let rollbacks = Arc::new(Mutex::new(Vec::new()));
        let rewinds = Arc::new(Mutex::new(Vec::new()));
        let store = Arc::new(ReconcileStore {
            head,
            restored,
            rollbacks: rollbacks.clone(),
        });
        let mut context = ToolContext::with_storage_store(
            everruns_provider::typed_id::SessionId::new(),
            Arc::new(MemorySecrets::default()),
        )
        .with_extension(Arc::new(
            crate::sandbox_checkpoint::SandboxCheckpointStoreExt(store),
        ));
        if install_durable_ext {
            context = context.with_extension(Arc::new(
                crate::sandbox_checkpoint::DurableToolResultStoreExt(Arc::new(FixedDurableStore(
                    durable,
                ))),
            ));
        }

        let state = SessionSandboxState {
            provider: "rewind-test-session-sandbox".to_string(),
            status: SessionSandboxStatus::Running,
            instance: test_instance("sb_reconcile"),
            init_completed_at: Some(now_rfc3339()),
            last_init_error: None,
            created_at: now_rfc3339(),
            updated_at: now_rfc3339(),
        };

        ReconcileHarness {
            context,
            state,
            rollbacks,
            rewinds: rewinds.clone(),
            provider: RewindProvider { rewinds },
        }
    }

    fn reconcile_config() -> SessionSandboxConfig {
        SessionSandboxConfig {
            provider: "rewind-test-session-sandbox".to_string(),
            auto_start: true,
            idle_pause_after_seconds: 180,
            provider_config: json!({}),
            init: SessionSandboxInitConfig { commands: vec![] },
        }
    }

    async fn run_reconcile(harness: &mut ReconcileHarness) {
        reconcile_session_sandbox_checkpoint(
            &harness.context,
            &harness.provider,
            &reconcile_config(),
            &mut harness.state,
        )
        .await
        .expect("reconciliation never fails the resume");
    }

    #[tokio::test]
    async fn reconcile_rolls_back_a_checkpoint_whose_tool_call_never_settled() {
        // The crash this issue is about: revision 2 is attached, but the tool
        // call that produced it is still claimed as running.
        let head = checkpoint_row("rev-2", Some(("turn-1", "call-2")));
        let head_id = head.id;
        let mut harness = reconcile_harness(
            Some(head),
            Some(checkpoint_row("rev-1", Some(("turn-1", "call-1")))),
            Some(everruns_core::durability::DurableToolCallStatus::Running),
            true,
        );

        run_reconcile(&mut harness).await;

        assert_eq!(*harness.rollbacks.lock().unwrap(), vec![(head_id, 7)]);
        assert_eq!(
            *harness.rewinds.lock().unwrap(),
            vec![Some("rev-1".to_string())]
        );
        assert_eq!(
            harness.state.instance.provider_state["recovery"]["head_revision"],
            json!("rev-1")
        );
    }

    #[tokio::test]
    async fn reconcile_clears_the_pointer_when_nothing_earlier_was_committed() {
        let mut harness = reconcile_harness(
            Some(checkpoint_row("rev-1", Some(("turn-1", "call-1")))),
            None,
            None,
            true,
        );

        run_reconcile(&mut harness).await;

        assert_eq!(harness.rollbacks.lock().unwrap().len(), 1);
        assert_eq!(*harness.rewinds.lock().unwrap(), vec![None]);
    }

    #[tokio::test]
    async fn reconcile_keeps_a_checkpoint_whose_tool_call_settled() {
        let mut harness = reconcile_harness(
            Some(checkpoint_row("rev-2", Some(("turn-1", "call-2")))),
            None,
            Some(everruns_core::durability::DurableToolCallStatus::Settled {
                result_json: json!({"ok": true}),
            }),
            true,
        );

        run_reconcile(&mut harness).await;

        assert!(harness.rollbacks.lock().unwrap().is_empty());
        assert!(harness.rewinds.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn reconcile_leaves_a_checkpoint_with_no_source_tool_call_alone() {
        // Nothing to compare it against, so distrusting it would be a guess.
        let mut harness = reconcile_harness(Some(checkpoint_row("rev-1", None)), None, None, true);

        run_reconcile(&mut harness).await;

        assert!(harness.rollbacks.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn reconcile_is_inert_without_the_durable_store() {
        // A host that cannot read durable state cannot decide, and must not
        // fall back to rolling back on suspicion.
        let mut harness = reconcile_harness(
            Some(checkpoint_row("rev-2", Some(("turn-1", "call-2")))),
            None,
            None,
            false,
        );

        run_reconcile(&mut harness).await;

        assert!(harness.rollbacks.lock().unwrap().is_empty());
        assert!(harness.rewinds.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn reconcile_is_inert_with_no_checkpoint_recorded() {
        let mut harness = reconcile_harness(None, None, None, true);

        run_reconcile(&mut harness).await;

        assert!(harness.rollbacks.lock().unwrap().is_empty());
        assert!(harness.rewinds.lock().unwrap().is_empty());
    }
}