apoc 0.3.0

Agentic process control for LLMs
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
//! SQLite-backed durable state.

use std::path::{Path, PathBuf};
use std::sync::Mutex;

use async_trait::async_trait;
use incurs_codemode::{ArtifactRef, ArtifactStore, ExecutionState, RuntimeStore, Snippet};
use rusqlite::{Connection, OptionalExtension, params};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use sha2::{Digest, Sha256};

use crate::model::{
    AgentSession, ArtifactMetadata, CausalEvent, Execution, Lease, ManagedRun, OperationReceipt,
    ProcessContext, ProcessController, ProcessDossier, ProcessEvent, ProcessEventQuery,
    ProcessInfo, Reservation, now_ms,
};

/// SQLite-backed durable apoc state store.
pub struct Store {
    connection: Mutex<Connection>,
    path: PathBuf,
}

/// Result of atomically claiming one execution idempotency key.
pub enum ExecutionClaim {
    /// This caller owns the new execution launch.
    Claimed,
    /// A prior caller already owns an identical execution launch.
    Replayed(Box<Execution>),
}

const DATABASE_VERSION: u32 = 3;

impl Store {
    /// Opens the default per-user apoc database.
    pub fn open_default() -> Result<Self, String> {
        Self::open(state_dir()?.join("apoc.sqlite3"))
    }

    /// Opens a SQLite database and applies the current schema.
    pub fn open(path: impl AsRef<Path>) -> Result<Self, String> {
        let path = path.as_ref().to_path_buf();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
        }
        backup_before_migration(&path)?;
        let connection = Connection::open(&path).map_err(|error| error.to_string())?;
        connection
            .busy_timeout(std::time::Duration::from_secs(5))
            .map_err(|error| error.to_string())?;
        connection
            .pragma_update(None, "journal_mode", "WAL")
            .map_err(|error| error.to_string())?;
        connection
            .pragma_update(None, "foreign_keys", "ON")
            .map_err(|error| error.to_string())?;
        connection
            .execute_batch(
                "
                CREATE TABLE IF NOT EXISTS runs (
                    id TEXT PRIMARY KEY,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS receipts (
                    id TEXT PRIMARY KEY,
                    kind TEXT NOT NULL,
                    value TEXT NOT NULL,
                    created_at INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS executions (
                    id TEXT PRIMARY KEY,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS snippets (
                    name TEXT PRIMARY KEY,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS artifacts (
                    id TEXT PRIMARY KEY,
                    execution_id TEXT NOT NULL,
                    value TEXT NOT NULL,
                    bytes INTEGER NOT NULL,
                    created_at INTEGER NOT NULL
                );
                CREATE INDEX IF NOT EXISTS artifacts_execution
                    ON artifacts(execution_id);
                CREATE TABLE IF NOT EXISTS recipes (
                    name TEXT PRIMARY KEY,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS connectors (
                    name TEXT PRIMARY KEY,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS providers (
                    name TEXT PRIMARY KEY,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS services (
                    name TEXT PRIMARY KEY,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS execution_records (
                    id TEXT PRIMARY KEY,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS execution_idempotency (
                    key TEXT PRIMARY KEY,
                    fingerprint TEXT NOT NULL,
                    execution_id TEXT NOT NULL UNIQUE,
                    created_at INTEGER NOT NULL,
                    FOREIGN KEY(execution_id) REFERENCES execution_records(id)
                );
                CREATE TABLE IF NOT EXISTS agent_sessions (
                    id TEXT PRIMARY KEY,
                    actor TEXT NOT NULL,
                    expires_at INTEGER NOT NULL,
                    closed INTEGER NOT NULL,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE INDEX IF NOT EXISTS agent_sessions_actor
                    ON agent_sessions(actor, updated_at DESC);
                CREATE TABLE IF NOT EXISTS leases (
                    id TEXT PRIMARY KEY,
                    owner_kind TEXT NOT NULL,
                    owner_id TEXT NOT NULL,
                    expires_at INTEGER,
                    released INTEGER NOT NULL,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE INDEX IF NOT EXISTS leases_owner
                    ON leases(owner_kind, owner_id, released);
                CREATE TABLE IF NOT EXISTS reservations (
                    id TEXT PRIMARY KEY,
                    kind TEXT NOT NULL,
                    key TEXT NOT NULL,
                    lease_id TEXT NOT NULL,
                    expires_at INTEGER,
                    released INTEGER NOT NULL,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE UNIQUE INDEX IF NOT EXISTS reservations_active_key
                    ON reservations(kind, key) WHERE released = 0;
                CREATE INDEX IF NOT EXISTS reservations_lease
                    ON reservations(lease_id, released);
                CREATE TABLE IF NOT EXISTS operation_receipts (
                    id TEXT PRIMARY KEY,
                    idempotency_key TEXT NOT NULL UNIQUE,
                    operation TEXT NOT NULL,
                    state TEXT NOT NULL,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS causal_payloads (
                    id TEXT PRIMARY KEY,
                    kind TEXT NOT NULL,
                    execution_id TEXT,
                    value TEXT,
                    bytes INTEGER NOT NULL,
                    created_at INTEGER NOT NULL,
                    accessed_at INTEGER NOT NULL,
                    pinned INTEGER NOT NULL,
                    pruned INTEGER NOT NULL
                );
                CREATE INDEX IF NOT EXISTS causal_payloads_retention
                    ON causal_payloads(pinned, pruned, accessed_at);
                CREATE TABLE IF NOT EXISTS causal_events (
                    sequence INTEGER PRIMARY KEY AUTOINCREMENT,
                    id TEXT NOT NULL UNIQUE,
                    at INTEGER NOT NULL,
                    kind TEXT NOT NULL,
                    subject TEXT NOT NULL,
                    actor TEXT NOT NULL,
                    correlation_id TEXT NOT NULL,
                    causation_id TEXT,
                    execution_id TEXT,
                    session_id TEXT,
                    payload_id TEXT,
                    details TEXT NOT NULL
                );
                CREATE INDEX IF NOT EXISTS causal_events_subject
                    ON causal_events(subject, sequence DESC);
                CREATE INDEX IF NOT EXISTS causal_events_execution
                    ON causal_events(execution_id, sequence DESC);
                CREATE INDEX IF NOT EXISTS causal_events_session
                    ON causal_events(session_id, sequence DESC);
                CREATE TABLE IF NOT EXISTS process_contexts (
                    key TEXT PRIMARY KEY,
                    pid INTEGER NOT NULL,
                    started_at INTEGER NOT NULL,
                    first_observed_at INTEGER NOT NULL,
                    last_observed_at INTEGER NOT NULL,
                    observations INTEGER NOT NULL,
                    origin TEXT NOT NULL,
                    run_id TEXT,
                    snapshot_id TEXT,
                    latest TEXT NOT NULL
                );
                CREATE INDEX IF NOT EXISTS process_contexts_pid
                    ON process_contexts(pid, started_at DESC);
                CREATE INDEX IF NOT EXISTS process_contexts_recent
                    ON process_contexts(last_observed_at DESC);
                CREATE TABLE IF NOT EXISTS process_events (
                    id TEXT PRIMARY KEY,
                    process_key TEXT NOT NULL,
                    at INTEGER NOT NULL,
                    operation TEXT NOT NULL,
                    phase TEXT NOT NULL,
                    actor TEXT NOT NULL,
                    execution_id TEXT,
                    run_id TEXT,
                    value TEXT NOT NULL
                );
                CREATE INDEX IF NOT EXISTS process_events_process
                    ON process_events(process_key, at DESC);
                CREATE INDEX IF NOT EXISTS process_events_recent
                    ON process_events(at DESC);
                ",
            )
            .map_err(|error| error.to_string())?;
        connection
            .execute(
                "INSERT OR IGNORE INTO providers(name, value, updated_at)
                 SELECT name, value, updated_at FROM connectors",
                [],
            )
            .map_err(|error| error.to_string())?;
        let added_execution = ensure_column(&connection, "process_events", "execution_id", "TEXT")?;
        let added_run = ensure_column(&connection, "process_events", "run_id", "TEXT")?;
        ensure_column(&connection, "process_contexts", "snapshot_id", "TEXT")?;
        if added_execution || added_run {
            connection
                .execute(
                    "UPDATE process_events SET
                        execution_id = json_extract(value, '$.controller.execution_id'),
                        run_id = json_extract(value, '$.run_id')
                     WHERE execution_id IS NULL OR run_id IS NULL",
                    [],
                )
                .map_err(|error| error.to_string())?;
        }
        connection
            .execute_batch(
                "
                CREATE INDEX IF NOT EXISTS process_events_operation
                    ON process_events(operation, at DESC);
                CREATE INDEX IF NOT EXISTS process_events_actor
                    ON process_events(actor, at DESC);
                CREATE INDEX IF NOT EXISTS process_events_execution
                    ON process_events(execution_id, at DESC);
                CREATE INDEX IF NOT EXISTS process_events_run
                    ON process_events(run_id, at DESC);
                ",
            )
            .map_err(|error| error.to_string())?;
        connection
            .pragma_update(None, "user_version", DATABASE_VERSION)
            .map_err(|error| error.to_string())?;
        Ok(Self {
            connection: Mutex::new(connection),
            path,
        })
    }

    /// Returns the database path.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Replaces one managed run.
    pub fn put_run(&self, run: &ManagedRun) -> Result<(), String> {
        self.put_named("runs", "id", &run.id, run)
    }

    /// Loads one managed run.
    pub fn get_run(&self, id: &str) -> Result<Option<ManagedRun>, String> {
        self.get_named("runs", "id", id)
    }

    /// Lists managed runs by most recent update.
    pub fn list_runs(&self) -> Result<Vec<ManagedRun>, String> {
        self.list_values("runs", "updated_at DESC")
    }

    /// Deletes one managed run.
    pub fn delete_run(&self, id: &str) -> Result<bool, String> {
        self.delete_named("runs", "id", id)
    }

    /// Stores a durable mutation or lifecycle receipt.
    pub fn put_receipt(&self, id: &str, kind: &str, value: &impl Serialize) -> Result<(), String> {
        let value = serde_json::to_string(value).map_err(|error| error.to_string())?;
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                "INSERT OR REPLACE INTO receipts(id, kind, value, created_at)
                 VALUES (?1, ?2, ?3, ?4)",
                params![id, kind, value, now_ms() as i64],
            )
            .map_err(|error| error.to_string())?;
        Ok(())
    }

    /// Loads one durable mutation receipt by its idempotency key.
    pub fn get_receipt<T: DeserializeOwned>(&self, id: &str) -> Result<Option<T>, String> {
        self.get_json_row("SELECT value FROM receipts WHERE id = ?1", id)
    }

    /// Replaces a named recipe.
    pub fn put_recipe(&self, name: &str, value: &Value) -> Result<(), String> {
        self.put_named("recipes", "name", name, value)
    }

    /// Loads a named recipe.
    pub fn get_recipe(&self, name: &str) -> Result<Option<Value>, String> {
        self.get_named("recipes", "name", name)
    }

    /// Lists every named recipe.
    pub fn list_recipes(&self) -> Result<Vec<Value>, String> {
        self.list_values("recipes", "name ASC")
    }

    /// Deletes a named recipe.
    pub fn delete_recipe(&self, name: &str) -> Result<bool, String> {
        self.delete_named("recipes", "name", name)
    }

    /// Replaces a named connector configuration.
    pub fn put_connector(&self, name: &str, value: &Value) -> Result<(), String> {
        self.put_provider(name, value)
    }

    /// Loads a named connector configuration.
    pub fn get_connector(&self, name: &str) -> Result<Option<Value>, String> {
        self.get_provider(name)?.map_or_else(
            || self.get_named("connectors", "name", name),
            |value| Ok(Some(value)),
        )
    }

    /// Lists every connector configuration.
    pub fn list_connectors(&self) -> Result<Vec<Value>, String> {
        self.list_providers()
    }

    /// Deletes a named connector configuration.
    pub fn delete_connector(&self, name: &str) -> Result<bool, String> {
        self.delete_provider(name)
    }

    /// Replaces a named capability-provider configuration.
    pub fn put_provider(&self, name: &str, value: &Value) -> Result<(), String> {
        self.put_named("providers", "name", name, value)
    }

    /// Loads a named capability-provider configuration.
    pub fn get_provider(&self, name: &str) -> Result<Option<Value>, String> {
        self.get_named("providers", "name", name)
    }

    /// Lists every capability-provider configuration.
    pub fn list_providers(&self) -> Result<Vec<Value>, String> {
        self.list_values("providers", "name ASC")
    }

    /// Deletes a named capability-provider configuration.
    pub fn delete_provider(&self, name: &str) -> Result<bool, String> {
        let removed = self.delete_named("providers", "name", name)?;
        let _ = self.delete_named("connectors", "name", name)?;
        Ok(removed)
    }

    /// Replaces a named service definition.
    pub fn put_service(&self, name: &str, value: &crate::model::Service) -> Result<(), String> {
        self.put_named("services", "name", name, value)
    }

    /// Loads a named service definition.
    pub fn get_service(&self, name: &str) -> Result<Option<crate::model::Service>, String> {
        self.get_named("services", "name", name)
    }

    /// Lists every service definition.
    pub fn list_services(&self) -> Result<Vec<crate::model::Service>, String> {
        self.list_values("services", "name ASC")
    }

    /// Deletes a named service definition.
    pub fn delete_service(&self, name: &str) -> Result<bool, String> {
        self.delete_named("services", "name", name)
    }

    /// Replaces one public execution record.
    pub fn put_execution_record(&self, execution: &Execution) -> Result<(), String> {
        self.put_named("execution_records", "id", &execution.id, execution)
    }

    /// Atomically stores a queued execution or returns the existing matching execution.
    pub fn claim_execution(
        &self,
        execution: &Execution,
        key: &str,
        fingerprint: &str,
    ) -> Result<ExecutionClaim, String> {
        let value = serde_json::to_string(execution).map_err(|error| error.to_string())?;
        let mut connection = self.connection.lock().map_err(|error| error.to_string())?;
        let transaction = connection
            .transaction()
            .map_err(|error| error.to_string())?;
        let existing = transaction
            .query_row(
                "SELECT fingerprint, execution_id FROM execution_idempotency WHERE key = ?1",
                [key],
                |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
            )
            .optional()
            .map_err(|error| error.to_string())?;
        if let Some((existing_fingerprint, execution_id)) = existing {
            if existing_fingerprint != fingerprint {
                return Err(format!(
                    "EXECUTION_IDEMPOTENCY_CONFLICT: key \"{key}\" already identifies a different execution request"
                ));
            }
            let existing = transaction
                .query_row(
                    "SELECT value FROM execution_records WHERE id = ?1",
                    [&execution_id],
                    |row| row.get::<_, String>(0),
                )
                .optional()
                .map_err(|error| error.to_string())?
                .ok_or_else(|| {
                    format!(
                        "EXECUTION_IDEMPOTENCY_CORRUPT: key \"{key}\" references missing execution \"{execution_id}\""
                    )
                })?;
            let existing = serde_json::from_str(&existing).map_err(|error| error.to_string())?;
            transaction.commit().map_err(|error| error.to_string())?;
            return Ok(ExecutionClaim::Replayed(Box::new(existing)));
        }
        transaction
            .execute(
                "INSERT INTO execution_records(id, value, updated_at) VALUES (?1, ?2, ?3)",
                params![execution.id, value, execution.updated_at as i64],
            )
            .map_err(|error| error.to_string())?;
        transaction
            .execute(
                "INSERT INTO execution_idempotency(key, fingerprint, execution_id, created_at)
                 VALUES (?1, ?2, ?3, ?4)",
                params![key, fingerprint, execution.id, execution.created_at as i64],
            )
            .map_err(|error| error.to_string())?;
        transaction.commit().map_err(|error| error.to_string())?;
        Ok(ExecutionClaim::Claimed)
    }

    /// Loads one public execution record.
    pub fn get_execution_record(&self, id: &str) -> Result<Option<Execution>, String> {
        self.get_named("execution_records", "id", id)
    }

    /// Lists public executions by most recent update.
    pub fn list_execution_records(&self) -> Result<Vec<Execution>, String> {
        self.list_values("execution_records", "updated_at DESC")
    }

    /// Lists one stable reverse-chronological page of public execution records.
    pub fn list_execution_records_page(
        &self,
        before: Option<(u64, &str)>,
        status: Option<&str>,
        limit: usize,
    ) -> Result<Vec<Execution>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let mut statement = connection
            .prepare(
                "SELECT value FROM execution_records
                 WHERE (?1 IS NULL OR json_extract(value, '$.status') = ?1)
                   AND (?2 IS NULL OR updated_at < ?2 OR (updated_at = ?2 AND id < ?3))
                 ORDER BY updated_at DESC, id DESC LIMIT ?4",
            )
            .map_err(|error| error.to_string())?;
        let (before_at, before_id) = before
            .map(|(at, id)| (Some(at as i64), Some(id)))
            .unwrap_or((None, None));
        let rows = statement
            .query_map(params![status, before_at, before_id, limit as i64], |row| {
                row.get::<_, String>(0)
            })
            .map_err(|error| error.to_string())?;
        deserialize_rows(rows)
    }

    /// Deletes one terminal public execution record.
    pub fn delete_execution_record(&self, id: &str) -> Result<bool, String> {
        let mut connection = self.connection.lock().map_err(|error| error.to_string())?;
        let transaction = connection
            .transaction()
            .map_err(|error| error.to_string())?;
        transaction
            .execute(
                "DELETE FROM execution_idempotency WHERE execution_id = ?1",
                [id],
            )
            .map_err(|error| error.to_string())?;
        let removed = transaction
            .execute("DELETE FROM execution_records WHERE id = ?1", [id])
            .map_err(|error| error.to_string())?
            > 0;
        transaction.commit().map_err(|error| error.to_string())?;
        Ok(removed)
    }

    /// Replaces one durable agent session.
    pub fn put_session(&self, session: &AgentSession) -> Result<(), String> {
        let value = serde_json::to_string(session).map_err(|error| error.to_string())?;
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                "INSERT OR REPLACE INTO agent_sessions(
                    id, actor, expires_at, closed, value, updated_at
                 ) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                params![
                    session.id,
                    session.actor,
                    session.expires_at.min(i64::MAX as u64) as i64,
                    session.closed,
                    value,
                    now_ms() as i64
                ],
            )
            .map_err(|error| error.to_string())?;
        Ok(())
    }

    /// Loads one durable agent session.
    pub fn get_session(&self, id: &str) -> Result<Option<AgentSession>, String> {
        self.get_json_row("SELECT value FROM agent_sessions WHERE id = ?1", id)
    }

    /// Lists durable agent sessions, optionally including closed and expired sessions.
    pub fn list_sessions(&self, active_only: bool) -> Result<Vec<AgentSession>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let sql = if active_only {
            "SELECT value FROM agent_sessions
             WHERE closed = 0 AND expires_at > ?1 ORDER BY updated_at DESC"
        } else {
            "SELECT value FROM agent_sessions
             WHERE ?1 >= 0 ORDER BY updated_at DESC"
        };
        let mut statement = connection.prepare(sql).map_err(|error| error.to_string())?;
        let rows = statement
            .query_map([now_ms().min(i64::MAX as u64) as i64], |row| {
                row.get::<_, String>(0)
            })
            .map_err(|error| error.to_string())?;
        deserialize_rows(rows)
    }

    /// Replaces one durable ownership lease.
    pub fn put_lease(&self, lease: &Lease) -> Result<(), String> {
        let value = serde_json::to_string(lease).map_err(|error| error.to_string())?;
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                "INSERT OR REPLACE INTO leases(
                    id, owner_kind, owner_id, expires_at, released, value, updated_at
                 ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                params![
                    lease.id,
                    enum_value(&lease.owner_kind)?,
                    lease.owner_id,
                    lease.expires_at.map(as_i64),
                    lease.released,
                    value,
                    now_ms() as i64
                ],
            )
            .map_err(|error| error.to_string())?;
        Ok(())
    }

    /// Loads one durable ownership lease.
    pub fn get_lease(&self, id: &str) -> Result<Option<Lease>, String> {
        self.get_json_row("SELECT value FROM leases WHERE id = ?1", id)
    }

    /// Lists leases, optionally limited to active records.
    pub fn list_leases(&self, active_only: bool) -> Result<Vec<Lease>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let sql = if active_only {
            "SELECT value FROM leases
             WHERE released = 0 AND (expires_at IS NULL OR expires_at > ?1)
             ORDER BY updated_at DESC"
        } else {
            "SELECT value FROM leases WHERE ?1 >= 0 ORDER BY updated_at DESC"
        };
        let mut statement = connection.prepare(sql).map_err(|error| error.to_string())?;
        let rows = statement
            .query_map([now_ms().min(i64::MAX as u64) as i64], |row| {
                row.get::<_, String>(0)
            })
            .map_err(|error| error.to_string())?;
        deserialize_rows(rows)
    }

    /// Releases a lease and every reservation that it owns atomically.
    pub fn release_lease(&self, id: &str) -> Result<Option<Lease>, String> {
        let Some(mut lease) = self.get_lease(id)? else {
            return Ok(None);
        };
        lease.released = true;
        lease.renewed_at = now_ms();
        let value = serde_json::to_string(&lease).map_err(|error| error.to_string())?;
        let mut connection = self.connection.lock().map_err(|error| error.to_string())?;
        let transaction = connection
            .transaction()
            .map_err(|error| error.to_string())?;
        transaction
            .execute(
                "UPDATE leases SET released = 1, value = ?2, updated_at = ?3 WHERE id = ?1",
                params![id, value, now_ms() as i64],
            )
            .map_err(|error| error.to_string())?;
        let mut statement = transaction
            .prepare("SELECT id, value FROM reservations WHERE lease_id = ?1 AND released = 0")
            .map_err(|error| error.to_string())?;
        let reservations = statement
            .query_map([id], |row| {
                Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
            })
            .map_err(|error| error.to_string())?
            .collect::<Result<Vec<_>, _>>()
            .map_err(|error| error.to_string())?;
        drop(statement);
        for (reservation_id, value) in reservations {
            let mut reservation =
                serde_json::from_str::<Reservation>(&value).map_err(|error| error.to_string())?;
            reservation.released = true;
            transaction
                .execute(
                    "UPDATE reservations SET released = 1, value = ?2, updated_at = ?3
                     WHERE id = ?1",
                    params![
                        reservation_id,
                        serde_json::to_string(&reservation).map_err(|error| error.to_string())?,
                        now_ms() as i64
                    ],
                )
                .map_err(|error| error.to_string())?;
        }
        transaction.commit().map_err(|error| error.to_string())?;
        Ok(Some(lease))
    }

    /// Acquires an apoc-local resource reservation atomically.
    pub fn acquire_reservation(&self, reservation: &Reservation) -> Result<Reservation, String> {
        let kind = enum_value(&reservation.kind)?;
        let now = now_ms();
        let mut connection = self.connection.lock().map_err(|error| error.to_string())?;
        let transaction = connection
            .transaction()
            .map_err(|error| error.to_string())?;
        let current = transaction
            .query_row(
                "SELECT value FROM reservations
                 WHERE kind = ?1 AND key = ?2 AND released = 0",
                params![kind, reservation.key],
                |row| row.get::<_, String>(0),
            )
            .optional()
            .map_err(|error| error.to_string())?;
        if let Some(value) = current {
            let current =
                serde_json::from_str::<Reservation>(&value).map_err(|error| error.to_string())?;
            if current.expires_at.is_none_or(|expires_at| expires_at > now) {
                return Err(format!(
                    "RESERVATION_CONFLICT: {} is owned by lease {}",
                    current.key, current.lease_id
                ));
            }
            transaction
                .execute(
                    "UPDATE reservations SET released = 1, updated_at = ?2 WHERE id = ?1",
                    params![current.id, now as i64],
                )
                .map_err(|error| error.to_string())?;
        }
        let value = serde_json::to_string(reservation).map_err(|error| error.to_string())?;
        transaction
            .execute(
                "INSERT INTO reservations(
                    id, kind, key, lease_id, expires_at, released, value, updated_at
                 ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                params![
                    reservation.id,
                    kind,
                    reservation.key,
                    reservation.lease_id,
                    reservation.expires_at.map(as_i64),
                    reservation.released,
                    value,
                    now as i64
                ],
            )
            .map_err(|error| error.to_string())?;
        transaction.commit().map_err(|error| error.to_string())?;
        Ok(reservation.clone())
    }

    /// Loads one resource reservation.
    pub fn get_reservation(&self, id: &str) -> Result<Option<Reservation>, String> {
        self.get_json_row("SELECT value FROM reservations WHERE id = ?1", id)
    }

    /// Lists reservations, optionally limited to active records.
    pub fn list_reservations(&self, active_only: bool) -> Result<Vec<Reservation>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let sql = if active_only {
            "SELECT value FROM reservations
             WHERE released = 0 AND (expires_at IS NULL OR expires_at > ?1)
             ORDER BY updated_at DESC"
        } else {
            "SELECT value FROM reservations WHERE ?1 >= 0 ORDER BY updated_at DESC"
        };
        let mut statement = connection.prepare(sql).map_err(|error| error.to_string())?;
        let rows = statement
            .query_map([now_ms().min(i64::MAX as u64) as i64], |row| {
                row.get::<_, String>(0)
            })
            .map_err(|error| error.to_string())?;
        deserialize_rows(rows)
    }

    /// Releases one resource reservation.
    pub fn release_reservation(&self, id: &str) -> Result<Option<Reservation>, String> {
        let Some(mut reservation) = self.get_reservation(id)? else {
            return Ok(None);
        };
        reservation.released = true;
        let value = serde_json::to_string(&reservation).map_err(|error| error.to_string())?;
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                "UPDATE reservations SET released = 1, value = ?2, updated_at = ?3
                 WHERE id = ?1",
                params![id, value, now_ms() as i64],
            )
            .map_err(|error| error.to_string())?;
        Ok(Some(reservation))
    }

    /// Stores an idempotent operation receipt.
    pub fn put_operation_receipt(&self, receipt: &OperationReceipt) -> Result<(), String> {
        let value = serde_json::to_string(receipt).map_err(|error| error.to_string())?;
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                "INSERT INTO operation_receipts(
                    id, idempotency_key, operation, state, value, updated_at
                 ) VALUES (?1, ?2, ?3, ?4, ?5, ?6)
                 ON CONFLICT(idempotency_key) DO UPDATE SET
                    state = excluded.state,
                    value = excluded.value,
                    updated_at = excluded.updated_at",
                params![
                    receipt.id,
                    receipt.idempotency_key,
                    receipt.operation,
                    enum_value(&receipt.state)?,
                    value,
                    now_ms() as i64
                ],
            )
            .map_err(|error| error.to_string())?;
        Ok(())
    }

    /// Loads an operation receipt by its receipt or idempotency identifier.
    pub fn operation_receipt(&self, key: &str) -> Result<Option<OperationReceipt>, String> {
        self.get_json_row(
            "SELECT value FROM operation_receipts WHERE idempotency_key = ?1 OR id = ?1",
            key,
        )
    }

    /// Lists recent operation receipts in reverse completion order.
    pub fn operation_receipts(&self, limit: usize) -> Result<Vec<OperationReceipt>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let mut statement = connection
            .prepare("SELECT value FROM operation_receipts ORDER BY updated_at DESC LIMIT ?1")
            .map_err(|error| error.to_string())?;
        let rows = statement
            .query_map([limit.min(i64::MAX as usize) as i64], |row| {
                row.get::<_, String>(0)
            })
            .map_err(|error| error.to_string())?;
        deserialize_rows(rows)
    }

    /// Appends one compact causal event and returns its durable sequence.
    pub fn append_causal_event(&self, mut event: CausalEvent) -> Result<CausalEvent, String> {
        let details = serde_json::to_string(&event.details).map_err(|error| error.to_string())?;
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        connection
            .execute(
                "INSERT INTO causal_events(
                    id, at, kind, subject, actor, correlation_id, causation_id,
                    execution_id, session_id, payload_id, details
                 ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
                params![
                    event.id,
                    event.at as i64,
                    event.kind,
                    event.subject,
                    event.actor,
                    event.correlation_id,
                    event.causation_id,
                    event.execution_id,
                    event.session_id,
                    event.payload_id,
                    details
                ],
            )
            .map_err(|error| error.to_string())?;
        event.sequence = connection.last_insert_rowid() as u64;
        Ok(event)
    }

    /// Lists causal events after a durable sequence cursor.
    pub fn causal_events(&self, after: u64, limit: usize) -> Result<Vec<CausalEvent>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let mut statement = connection
            .prepare(
                "SELECT sequence, id, at, kind, subject, actor, correlation_id,
                        causation_id, execution_id, session_id, payload_id, details
                 FROM causal_events WHERE sequence > ?1 ORDER BY sequence ASC LIMIT ?2",
            )
            .map_err(|error| error.to_string())?;
        let rows = statement
            .query_map(
                params![as_i64(after), limit.min(i64::MAX as usize) as i64],
                causal_event,
            )
            .map_err(|error| error.to_string())?;
        rows.collect::<Result<Vec<_>, _>>()
            .map_err(|error| error.to_string())
    }

    /// Lists newest causal events for one exact subject key.
    pub fn causal_events_for_subject(
        &self,
        subject: &str,
        limit: usize,
    ) -> Result<Vec<CausalEvent>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let mut statement = connection
            .prepare(
                "SELECT sequence, id, at, kind, subject, actor, correlation_id,
                        causation_id, execution_id, session_id, payload_id, details
                 FROM causal_events WHERE subject = ?1
                 ORDER BY sequence DESC LIMIT ?2",
            )
            .map_err(|error| error.to_string())?;
        let rows = statement
            .query_map(
                params![subject, limit.min(i64::MAX as usize) as i64],
                causal_event,
            )
            .map_err(|error| error.to_string())?;
        rows.collect::<Result<Vec<_>, _>>()
            .map_err(|error| error.to_string())
    }

    /// Stores a content-addressed causal payload.
    pub fn put_causal_payload(
        &self,
        kind: &str,
        execution_id: Option<&str>,
        value: &Value,
    ) -> Result<ArtifactMetadata, String> {
        let value = serde_json::to_string(value).map_err(|error| error.to_string())?;
        let id = format!(
            "{:x}",
            Sha256::digest([kind.as_bytes(), value.as_bytes()].concat())
        );
        let now = now_ms();
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                "INSERT INTO causal_payloads(
                    id, kind, execution_id, value, bytes, created_at, accessed_at, pinned, pruned
                 ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, 0, 0)
                 ON CONFLICT(id) DO UPDATE SET accessed_at = excluded.accessed_at",
                params![
                    id,
                    kind,
                    execution_id,
                    value,
                    value.len() as i64,
                    now as i64
                ],
            )
            .map_err(|error| error.to_string())?;
        Ok(ArtifactMetadata {
            id,
            kind: kind.to_string(),
            execution_id: execution_id.map(str::to_string),
            bytes: value.len() as u64,
            created_at: now,
            accessed_at: now,
            pinned: false,
            pruned: false,
        })
    }

    /// Loads retained causal payload bytes.
    pub fn causal_payload(&self, id: &str) -> Result<Option<Value>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let value = connection
            .query_row(
                "SELECT value FROM causal_payloads WHERE id = ?1 AND pruned = 0",
                [id],
                |row| row.get::<_, Option<String>>(0),
            )
            .optional()
            .map_err(|error| error.to_string())?
            .flatten();
        if value.is_some() {
            connection
                .execute(
                    "UPDATE causal_payloads SET accessed_at = ?2 WHERE id = ?1",
                    params![id, now_ms() as i64],
                )
                .map_err(|error| error.to_string())?;
        }
        value
            .map(|value| serde_json::from_str(&value).map_err(|error| error.to_string()))
            .transpose()
    }

    /// Pins or unpins one causal payload.
    pub fn pin_causal_payload(&self, id: &str, pinned: bool) -> Result<bool, String> {
        Ok(self
            .connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                "UPDATE causal_payloads SET pinned = ?2, accessed_at = ?3 WHERE id = ?1",
                params![id, pinned, now_ms() as i64],
            )
            .map_err(|error| error.to_string())?
            > 0)
    }

    /// Prunes unpinned payload bytes older than the supplied timestamp.
    pub fn prune_causal_payloads(&self, before: u64) -> Result<usize, String> {
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                "UPDATE causal_payloads SET value = NULL, pruned = 1
                 WHERE pinned = 0 AND pruned = 0 AND accessed_at < ?1",
                [as_i64(before)],
            )
            .map_err(|error| error.to_string())
    }

    /// Prunes least-recently-accessed unpinned payloads until retained bytes fit a limit.
    pub fn prune_causal_payloads_to_size(&self, max_bytes: u64) -> Result<usize, String> {
        let mut connection = self.connection.lock().map_err(|error| error.to_string())?;
        let transaction = connection
            .transaction()
            .map_err(|error| error.to_string())?;
        let mut retained = transaction
            .query_row(
                "SELECT COALESCE(SUM(bytes), 0) FROM causal_payloads WHERE pruned = 0",
                [],
                |row| row.get::<_, i64>(0),
            )
            .map_err(|error| error.to_string())?
            .max(0) as u64;
        if retained <= max_bytes {
            return Ok(0);
        }
        let payloads = {
            let mut statement = transaction
                .prepare(
                    "SELECT id, bytes FROM causal_payloads
                     WHERE pinned = 0 AND pruned = 0
                     ORDER BY accessed_at ASC, created_at ASC",
                )
                .map_err(|error| error.to_string())?;
            let rows = statement
                .query_map([], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, i64>(1)?.max(0) as u64,
                    ))
                })
                .map_err(|error| error.to_string())?;
            rows.collect::<Result<Vec<_>, _>>()
                .map_err(|error| error.to_string())?
        };
        let mut pruned = 0;
        for (id, bytes) in payloads {
            if retained <= max_bytes {
                break;
            }
            transaction
                .execute(
                    "UPDATE causal_payloads SET value = NULL, pruned = 1 WHERE id = ?1",
                    [id],
                )
                .map_err(|error| error.to_string())?;
            retained = retained.saturating_sub(bytes);
            pruned += 1;
        }
        transaction.commit().map_err(|error| error.to_string())?;
        Ok(pruned)
    }

    /// Records one interaction for every supplied stable process identity.
    #[allow(clippy::too_many_arguments)]
    pub fn record_processes(
        &self,
        processes: &[ProcessInfo],
        operation: &str,
        phase: &str,
        selector: Option<&str>,
        controller: &ProcessController,
        origin: &str,
        managed_execution_id: Option<&str>,
        details: &Value,
    ) -> Result<Vec<ProcessEvent>, String> {
        self.record_processes_with_details(
            processes,
            operation,
            phase,
            selector,
            controller,
            origin,
            managed_execution_id,
            &vec![details.clone(); processes.len()],
        )
    }

    /// Records process interactions with one detail value per process.
    #[allow(clippy::too_many_arguments)]
    pub fn record_processes_with_details(
        &self,
        processes: &[ProcessInfo],
        operation: &str,
        phase: &str,
        selector: Option<&str>,
        controller: &ProcessController,
        origin: &str,
        managed_execution_id: Option<&str>,
        details: &[Value],
    ) -> Result<Vec<ProcessEvent>, String> {
        if processes.len() != details.len() {
            return Err("Process snapshots and event details must have equal lengths".to_string());
        }
        let at = now_ms();
        let mut connection = self.connection.lock().map_err(|error| error.to_string())?;
        let transaction = connection
            .transaction()
            .map_err(|error| error.to_string())?;
        let mut events = Vec::with_capacity(processes.len());
        for (process, details) in processes.iter().zip(details) {
            let key = process_key(&process.identity);
            let latest = serde_json::to_string(process).map_err(|error| error.to_string())?;
            let snapshot_id = format!("{:x}", Sha256::digest(latest.as_bytes()));
            transaction
                .execute(
                    "INSERT OR IGNORE INTO causal_payloads(
                        id, kind, execution_id, value, bytes, created_at, accessed_at, pinned, pruned
                     ) VALUES (?1, 'process_snapshot', ?2, ?3, ?4, ?5, ?5, 0, 0)",
                    params![
                        snapshot_id,
                        controller.execution_id,
                        latest,
                        latest.len() as i64,
                        at as i64
                    ],
                )
                .map_err(|error| error.to_string())?;
            transaction
                .execute(
                    "INSERT INTO process_contexts(
                        key, pid, started_at, first_observed_at, last_observed_at,
                        observations, origin, run_id, snapshot_id, latest
                     ) VALUES (?1, ?2, ?3, ?4, ?4, 1, ?5, ?6, ?7, ?8)
                     ON CONFLICT(key) DO UPDATE SET
                        last_observed_at = excluded.last_observed_at,
                        observations = process_contexts.observations + 1,
                        origin = CASE
                            WHEN excluded.origin = 'observed' THEN process_contexts.origin
                            ELSE excluded.origin
                        END,
                        run_id = COALESCE(excluded.run_id, process_contexts.run_id),
                        snapshot_id = excluded.snapshot_id,
                        latest = CASE
                            WHEN process_contexts.snapshot_id = excluded.snapshot_id
                                THEN process_contexts.latest
                            ELSE excluded.latest
                        END",
                    params![
                        key,
                        process.identity.pid as i64,
                        process.identity.started_at as i64,
                        at as i64,
                        origin,
                        managed_execution_id,
                        snapshot_id,
                        latest
                    ],
                )
                .map_err(|error| error.to_string())?;
            let event = ProcessEvent {
                id: uuid::Uuid::now_v7().to_string(),
                process_key: key,
                at,
                operation: operation.to_string(),
                phase: phase.to_string(),
                selector: selector.map(str::to_string),
                controller: controller.clone(),
                execution_id: managed_execution_id.map(str::to_string),
                details: details.clone(),
            };
            transaction
                .execute(
                    "INSERT INTO process_events(
                        id, process_key, at, operation, phase, actor,
                        execution_id, run_id, value
                     ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
                    params![
                        event.id,
                        event.process_key,
                        event.at as i64,
                        event.operation,
                        event.phase,
                        event.controller.actor,
                        event.controller.execution_id,
                        event.execution_id,
                        serde_json::to_string(&event).map_err(|error| error.to_string())?
                    ],
                )
                .map_err(|error| error.to_string())?;
            transaction
                .execute(
                    "INSERT INTO causal_events(
                        id, at, kind, subject, actor, correlation_id, causation_id,
                        execution_id, session_id, payload_id, details
                     ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, NULL, ?7, NULL, ?8, ?9)",
                    params![
                        event.id,
                        event.at as i64,
                        format!("{}.{}", event.operation, event.phase),
                        event.process_key,
                        event.controller.actor,
                        event.controller.invocation_id,
                        event.controller.execution_id,
                        snapshot_id,
                        serde_json::to_string(&serde_json::json!({
                            "selector": &event.selector,
                            "execution_id": &event.execution_id,
                            "details": &event.details
                        }))
                        .map_err(|error| error.to_string())?
                    ],
                )
                .map_err(|error| error.to_string())?;
            events.push(event);
        }
        transaction.commit().map_err(|error| error.to_string())?;
        Ok(events)
    }

    /// Returns context and recent events for one exact process key.
    pub fn process_dossier(&self, key: &str, event_limit: usize) -> Result<ProcessDossier, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let context = connection
            .query_row(
                "SELECT key, first_observed_at, last_observed_at, observations,
                        origin, run_id, snapshot_id, latest
                 FROM process_contexts WHERE key = ?1",
                [key],
                process_context,
            )
            .optional()
            .map_err(|error| error.to_string())?
            .ok_or_else(|| format!("No recorded process context for \"{key}\""))?;
        let events = process_events(&connection, Some(key), event_limit)?;
        Ok(ProcessDossier { context, events })
    }

    /// Returns newest contexts for every recorded lifetime of one PID.
    pub fn process_dossiers_for_pid(
        &self,
        pid: u32,
        event_limit: usize,
    ) -> Result<Vec<ProcessDossier>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let mut statement = connection
            .prepare(
                "SELECT key, first_observed_at, last_observed_at, observations,
                        origin, run_id, snapshot_id, latest
                 FROM process_contexts WHERE pid = ?1 ORDER BY started_at DESC",
            )
            .map_err(|error| error.to_string())?;
        let contexts = statement
            .query_map([pid as i64], process_context)
            .map_err(|error| error.to_string())?
            .collect::<Result<Vec<_>, _>>()
            .map_err(|error| error.to_string())?;
        contexts
            .into_iter()
            .map(|context| {
                let events = process_events(&connection, Some(&context.key), event_limit)?;
                Ok(ProcessDossier { context, events })
            })
            .collect()
    }

    /// Lists recently recorded process interactions across all identities.
    pub fn list_process_events(&self, limit: usize) -> Result<Vec<ProcessEvent>, String> {
        self.query_process_events(&ProcessEventQuery {
            limit,
            ..ProcessEventQuery::default()
        })
    }

    /// Lists newest process interactions matching indexed agent filters.
    pub fn query_process_events(
        &self,
        query: &ProcessEventQuery,
    ) -> Result<Vec<ProcessEvent>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let mut sql = "SELECT value FROM process_events WHERE 1 = 1".to_string();
        let mut values = Vec::<Box<dyn rusqlite::ToSql>>::new();
        if let Some(value) = &query.process_key {
            sql.push_str(" AND process_key = ?");
            values.push(Box::new(value.clone()));
        }
        if let Some(value) = query.pid {
            sql.push_str(" AND process_key LIKE ?");
            values.push(Box::new(format!("%:{value}@%")));
        }
        if let Some(value) = &query.operation {
            sql.push_str(" AND operation = ?");
            values.push(Box::new(value.clone()));
        }
        if let Some(value) = &query.phase {
            sql.push_str(" AND phase = ?");
            values.push(Box::new(value.clone()));
        }
        if let Some(value) = &query.actor {
            sql.push_str(" AND actor = ?");
            values.push(Box::new(value.clone()));
        }
        if let Some(value) = &query.controller_execution_id {
            sql.push_str(" AND execution_id = ?");
            values.push(Box::new(value.clone()));
        }
        if let Some(value) = &query.execution_id {
            sql.push_str(" AND run_id = ?");
            values.push(Box::new(value.clone()));
        }
        if let Some(value) = query.since_ms {
            sql.push_str(" AND at >= ?");
            values.push(Box::new(value.min(i64::MAX as u64) as i64));
        }
        if let Some(value) = query.until_ms {
            sql.push_str(" AND at <= ?");
            values.push(Box::new(value.min(i64::MAX as u64) as i64));
        }
        sql.push_str(" ORDER BY at DESC LIMIT ?");
        values.push(Box::new(query.limit.min(i64::MAX as usize) as i64));
        let mut statement = connection
            .prepare(&sql)
            .map_err(|error| error.to_string())?;
        let rows = statement
            .query_map(
                rusqlite::params_from_iter(values.iter().map(|value| value.as_ref())),
                |row| row.get::<_, String>(0),
            )
            .map_err(|error| error.to_string())?;
        rows.map(|row| {
            let value = row.map_err(|error| error.to_string())?;
            serde_json::from_str(&value).map_err(|error| error.to_string())
        })
        .collect()
    }

    fn put_named(
        &self,
        table: &str,
        key: &str,
        name: &str,
        value: &impl Serialize,
    ) -> Result<(), String> {
        require_table(table, key)?;
        let value = serde_json::to_string(value).map_err(|error| error.to_string())?;
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                &format!(
                    "INSERT OR REPLACE INTO {table}({key}, value, updated_at)
                     VALUES (?1, ?2, ?3)"
                ),
                params![name, value, now_ms() as i64],
            )
            .map_err(|error| error.to_string())?;
        Ok(())
    }

    fn get_json_row<T: DeserializeOwned>(&self, sql: &str, key: &str) -> Result<Option<T>, String> {
        let value = self
            .connection
            .lock()
            .map_err(|error| error.to_string())?
            .query_row(sql, [key], |row| row.get::<_, String>(0))
            .optional()
            .map_err(|error| error.to_string())?;
        value
            .map(|value| serde_json::from_str(&value).map_err(|error| error.to_string()))
            .transpose()
    }

    fn get_named<T: DeserializeOwned>(
        &self,
        table: &str,
        key: &str,
        name: &str,
    ) -> Result<Option<T>, String> {
        require_table(table, key)?;
        let value = self
            .connection
            .lock()
            .map_err(|error| error.to_string())?
            .query_row(
                &format!("SELECT value FROM {table} WHERE {key} = ?1"),
                [name],
                |row| row.get::<_, String>(0),
            )
            .optional()
            .map_err(|error| error.to_string())?;
        value
            .map(|value| serde_json::from_str(&value).map_err(|error| error.to_string()))
            .transpose()
    }

    fn list_values<T: DeserializeOwned>(&self, table: &str, order: &str) -> Result<Vec<T>, String> {
        require_list(table, order)?;
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let mut statement = connection
            .prepare(&format!("SELECT value FROM {table} ORDER BY {order}"))
            .map_err(|error| error.to_string())?;
        let rows = statement
            .query_map([], |row| row.get::<_, String>(0))
            .map_err(|error| error.to_string())?;
        rows.map(|row| {
            let value = row.map_err(|error| error.to_string())?;
            serde_json::from_str(&value).map_err(|error| error.to_string())
        })
        .collect()
    }

    fn delete_named(&self, table: &str, key: &str, name: &str) -> Result<bool, String> {
        require_table(table, key)?;
        Ok(self
            .connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(&format!("DELETE FROM {table} WHERE {key} = ?1"), [name])
            .map_err(|error| error.to_string())?
            > 0)
    }
}

fn backup_before_migration(path: &Path) -> Result<(), String> {
    if !path.exists() || path.metadata().map_err(|error| error.to_string())?.len() == 0 {
        return Ok(());
    }
    let connection = Connection::open(path).map_err(|error| error.to_string())?;
    let version = connection
        .pragma_query_value(None, "user_version", |row| row.get::<_, u32>(0))
        .map_err(|error| error.to_string())?;
    let tables = connection
        .query_row(
            "SELECT EXISTS(
                SELECT 1 FROM sqlite_master
                WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
             )",
            [],
            |row| row.get::<_, bool>(0),
        )
        .map_err(|error| error.to_string())?;
    if version >= DATABASE_VERSION || !tables {
        return Ok(());
    }
    connection
        .execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")
        .map_err(|error| error.to_string())?;
    drop(connection);
    let destination = DATABASE_VERSION;
    let backup = PathBuf::from(format!(
        "{}.pre-v{destination}-{}.sqlite3",
        path.display(),
        now_ms()
    ));
    std::fs::copy(path, &backup).map_err(|error| {
        format!(
            "Could not back up database before v{destination} migration {} to {}: {error}",
            path.display(),
            backup.display()
        )
    })?;
    Ok(())
}

fn process_key(identity: &crate::model::ProcessIdentity) -> String {
    crate::process::process_context_key(identity)
}

fn ensure_column(
    connection: &Connection,
    table: &str,
    column: &str,
    kind: &str,
) -> Result<bool, String> {
    let mut statement = connection
        .prepare(&format!("PRAGMA table_info({table})"))
        .map_err(|error| error.to_string())?;
    let columns = statement
        .query_map([], |row| row.get::<_, String>(1))
        .map_err(|error| error.to_string())?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| error.to_string())?;
    if !columns.iter().any(|value| value == column) {
        connection
            .execute(
                &format!("ALTER TABLE {table} ADD COLUMN {column} {kind}"),
                [],
            )
            .map_err(|error| error.to_string())?;
        return Ok(true);
    }
    Ok(false)
}

fn process_context(row: &rusqlite::Row<'_>) -> rusqlite::Result<ProcessContext> {
    let latest = row.get::<_, String>(7)?;
    let latest = serde_json::from_str::<ProcessInfo>(&latest).map_err(|error| {
        rusqlite::Error::FromSqlConversionFailure(7, rusqlite::types::Type::Text, Box::new(error))
    })?;
    Ok(ProcessContext {
        key: row.get(0)?,
        first_observed_at: row.get::<_, i64>(1)? as u64,
        last_observed_at: row.get::<_, i64>(2)? as u64,
        observations: row.get::<_, i64>(3)? as u64,
        snapshot_id: row.get(6)?,
        origin: row.get(4)?,
        execution_id: row.get(5)?,
        latest,
    })
}

fn process_events(
    connection: &Connection,
    key: Option<&str>,
    limit: usize,
) -> Result<Vec<ProcessEvent>, String> {
    let (sql, parameter): (&str, Box<dyn rusqlite::ToSql>) = if let Some(key) = key {
        (
            "SELECT value FROM process_events
             WHERE process_key = ?1 ORDER BY at DESC LIMIT ?2",
            Box::new(key.to_string()),
        )
    } else {
        (
            "SELECT value FROM process_events
             WHERE ?1 IS NULL ORDER BY at DESC LIMIT ?2",
            Box::new(rusqlite::types::Null),
        )
    };
    let mut statement = connection.prepare(sql).map_err(|error| error.to_string())?;
    let rows = statement
        .query_map(
            rusqlite::params_from_iter([
                parameter.as_ref(),
                &(limit.min(i64::MAX as usize) as i64) as &dyn rusqlite::ToSql,
            ]),
            |row| row.get::<_, String>(0),
        )
        .map_err(|error| error.to_string())?;
    rows.map(|row| {
        let value = row.map_err(|error| error.to_string())?;
        serde_json::from_str(&value).map_err(|error| error.to_string())
    })
    .collect()
}

fn causal_event(row: &rusqlite::Row<'_>) -> rusqlite::Result<CausalEvent> {
    let details = row.get::<_, String>(11)?;
    let details = serde_json::from_str(&details).map_err(|error| {
        rusqlite::Error::FromSqlConversionFailure(11, rusqlite::types::Type::Text, Box::new(error))
    })?;
    Ok(CausalEvent {
        sequence: row.get::<_, i64>(0)? as u64,
        id: row.get(1)?,
        at: row.get::<_, i64>(2)? as u64,
        kind: row.get(3)?,
        subject: row.get(4)?,
        actor: row.get(5)?,
        correlation_id: row.get(6)?,
        causation_id: row.get(7)?,
        execution_id: row.get(8)?,
        session_id: row.get(9)?,
        payload_id: row.get(10)?,
        details,
    })
}

fn deserialize_rows<T: DeserializeOwned>(
    rows: impl Iterator<Item = rusqlite::Result<String>>,
) -> Result<Vec<T>, String> {
    rows.map(|row| {
        let value = row.map_err(|error| error.to_string())?;
        serde_json::from_str(&value).map_err(|error| error.to_string())
    })
    .collect()
}

fn enum_value(value: &impl Serialize) -> Result<String, String> {
    serde_json::to_value(value)
        .map_err(|error| error.to_string())?
        .as_str()
        .map(str::to_string)
        .ok_or_else(|| "Expected a string-backed enum".to_string())
}

fn as_i64(value: u64) -> i64 {
    value.min(i64::MAX as u64) as i64
}

#[async_trait]
impl RuntimeStore for Store {
    async fn get_execution(&self, id: &str) -> Result<Option<ExecutionState>, String> {
        self.get_named("executions", "id", id)
    }

    async fn put_execution(&self, execution: &ExecutionState) -> Result<(), String> {
        self.put_named("executions", "id", &execution.id, execution)
    }

    async fn list_executions(&self) -> Result<Vec<ExecutionState>, String> {
        self.list_values("executions", "updated_at DESC")
    }

    async fn delete_execution(&self, id: &str) -> Result<(), String> {
        self.delete_named("executions", "id", id)?;
        Ok(())
    }

    async fn get_snippet(&self, name: &str) -> Result<Option<Snippet>, String> {
        self.get_named("snippets", "name", name)
    }

    async fn put_snippet(&self, snippet: &Snippet) -> Result<(), String> {
        self.put_named("snippets", "name", &snippet.name, snippet)
    }

    async fn list_snippets(&self) -> Result<Vec<Snippet>, String> {
        self.list_values("snippets", "name ASC")
    }

    async fn delete_snippet(&self, name: &str) -> Result<bool, String> {
        self.delete_named("snippets", "name", name)
    }
}

#[async_trait]
impl ArtifactStore for Store {
    async fn put(&self, execution_id: &str, value: &Value) -> Result<ArtifactRef, String> {
        let value = serde_json::to_string(value).map_err(|error| error.to_string())?;
        let bytes = value.len();
        let id = format!(
            "{:x}",
            Sha256::digest([execution_id.as_bytes(), value.as_bytes()].concat())
        );
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                "INSERT OR REPLACE INTO artifacts(id, execution_id, value, bytes, created_at)
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                params![id, execution_id, value, bytes as i64, now_ms() as i64],
            )
            .map_err(|error| error.to_string())?;
        Ok(ArtifactRef {
            id,
            execution_id: execution_id.to_string(),
            bytes,
            preview: truncate(&value, 512),
        })
    }

    async fn get(&self, execution_id: &str, artifact_id: &str) -> Result<Option<Value>, String> {
        let value = self
            .connection
            .lock()
            .map_err(|error| error.to_string())?
            .query_row(
                "SELECT value FROM artifacts WHERE id = ?1 AND execution_id = ?2",
                params![artifact_id, execution_id],
                |row| row.get::<_, String>(0),
            )
            .optional()
            .map_err(|error| error.to_string())?;
        value
            .map(|value| serde_json::from_str(&value).map_err(|error| error.to_string()))
            .transpose()
    }

    async fn delete_execution(&self, execution_id: &str) -> Result<(), String> {
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                "DELETE FROM artifacts WHERE execution_id = ?1",
                [execution_id],
            )
            .map_err(|error| error.to_string())?;
        Ok(())
    }
}

/// Returns the persistent per-user apoc directory.
pub fn state_dir() -> Result<PathBuf, String> {
    if let Some(path) = std::env::var_os("APOC_HOME") {
        return Ok(PathBuf::from(path));
    }
    dirs::data_dir()
        .map(|path| path.join("apoc"))
        .ok_or_else(|| "Cannot determine the per-user application data directory".to_string())
}

/// Returns the private per-user runtime directory.
pub fn runtime_dir() -> PathBuf {
    if let Some(path) = std::env::var_os("APOC_RUNTIME_DIR") {
        return PathBuf::from(path);
    }
    std::env::temp_dir().join(format!("apoc-{}", unsafe { libc::geteuid() }))
}

fn require_table(table: &str, key: &str) -> Result<(), String> {
    if matches!(
        (table, key),
        ("runs", "id")
            | ("executions", "id")
            | ("execution_records", "id")
            | ("snippets", "name")
            | ("recipes", "name")
            | ("connectors", "name")
            | ("providers", "name")
            | ("services", "name")
    ) {
        Ok(())
    } else {
        Err("Unsupported state table".to_string())
    }
}

fn require_list(table: &str, order: &str) -> Result<(), String> {
    if matches!(
        (table, order),
        ("runs", "updated_at DESC")
            | ("executions", "updated_at DESC")
            | ("execution_records", "updated_at DESC")
            | ("snippets", "name ASC")
            | ("recipes", "name ASC")
            | ("connectors", "name ASC")
            | ("providers", "name ASC")
            | ("services", "name ASC")
    ) {
        Ok(())
    } else {
        Err("Unsupported state list".to_string())
    }
}

fn truncate(value: &str, max: usize) -> String {
    if value.len() <= max {
        return value.to_string();
    }
    let mut end = max;
    while !value.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}...", &value[..end])
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use tempfile::tempdir;

    use super::*;
    use crate::model::{IoMode, Reservation, ReservationKind, RestartPolicy, RunLifetime, RunSpec};

    #[test]
    fn backs_up_an_unversioned_database_before_migration() {
        let directory = tempdir().unwrap();
        let path = directory.path().join("state.sqlite3");
        let connection = Connection::open(&path).unwrap();
        connection
            .execute_batch("CREATE TABLE legacy_state (id TEXT PRIMARY KEY);")
            .unwrap();
        drop(connection);

        drop(Store::open(&path).unwrap());

        let backups = std::fs::read_dir(directory.path())
            .unwrap()
            .map(|entry| entry.unwrap().file_name().to_string_lossy().to_string())
            .filter(|name| name.starts_with("state.sqlite3.pre-v3-"))
            .collect::<Vec<_>>();
        assert_eq!(backups.len(), 1);
        let connection = Connection::open(path).unwrap();
        let version = connection
            .pragma_query_value(None, "user_version", |row| row.get::<_, u32>(0))
            .unwrap();
        assert_eq!(version, 3);
    }

    #[test]
    fn migrates_v1_connectors_into_providers() {
        let directory = tempdir().unwrap();
        let path = directory.path().join("state.sqlite3");
        let connection = Connection::open(&path).unwrap();
        connection
            .execute_batch(
                "CREATE TABLE connectors (
                    name TEXT PRIMARY KEY,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                 );
                 INSERT INTO connectors(name, value, updated_at) VALUES (
                    'fixture',
                    '{\"name\":\"fixture\",\"kind\":\"mcp_http\",\"url\":\"http://localhost/mcp\",\"base_url\":null,\"headers\":{},\"instructions\":null,\"created_at\":1,\"updated_at\":1}',
                    1
                 );
                 PRAGMA user_version = 1;",
            )
            .unwrap();
        drop(connection);

        let store = Store::open(&path).unwrap();
        let backups = std::fs::read_dir(directory.path())
            .unwrap()
            .map(|entry| entry.unwrap().file_name().to_string_lossy().to_string())
            .filter(|name| name.starts_with("state.sqlite3.pre-v3-"))
            .collect::<Vec<_>>();
        assert_eq!(backups.len(), 1);
        let providers = store.list_providers().unwrap();
        assert_eq!(providers.len(), 1);
        let provider =
            serde_json::from_value::<crate::model::ProviderConfig>(providers[0].clone()).unwrap();
        assert_eq!(provider.name, "fixture");
        assert_eq!(provider.kind, crate::model::ProviderKind::McpHttp);
        assert!(store.get_connector("fixture").unwrap().is_some());
    }

    #[test]
    fn persists_managed_runs() {
        let directory = tempdir().unwrap();
        let store = Store::open(directory.path().join("state.sqlite3")).unwrap();
        let run = ManagedRun {
            id: "run-1".to_string(),
            spec: RunSpec {
                name: "fixture".to_string(),
                purpose: None,
                labels: BTreeMap::new(),
                requested_by: None,
                argv: vec!["true".to_string()],
                cwd: None,
                env: BTreeMap::new(),
                shell: false,
                io: IoMode::Pipes,
                lifetime: RunLifetime::Persistent,
                restart: RestartPolicy::Never,
                timeout_ms: None,
                replicas: 1,
                max_attempts: 1,
                retry_backoff_ms: 500,
                retry_max_backoff_ms: 30_000,
            },
            status: "running".to_string(),
            processes: Vec::new(),
            process_history: Vec::new(),
            created_at: 1,
            updated_at: 1,
            exit_code: None,
            stdout_path: None,
            stderr_path: None,
        };
        store.put_run(&run).unwrap();
        assert_eq!(
            store.get_run("run-1").unwrap().unwrap().spec.name,
            "fixture"
        );
        assert_eq!(store.list_runs().unwrap().len(), 1);
    }

    #[test]
    fn filters_process_history_by_execution_and_operation() {
        let directory = tempdir().unwrap();
        let store = Store::open(directory.path().join("state.sqlite3")).unwrap();
        let process = crate::process::process_info_for_pid(std::process::id()).unwrap();
        let controller = ProcessController::capture(true, Some("execution-42".to_string()));
        store
            .record_processes(
                std::slice::from_ref(&process),
                "process.get",
                "observed",
                Some(&format!("pid:{}", process.identity.pid)),
                &controller,
                "observed",
                Some("managed-7"),
                &serde_json::json!({}),
            )
            .unwrap();
        let events = store
            .query_process_events(&ProcessEventQuery {
                limit: 10,
                operation: Some("process.get".to_string()),
                controller_execution_id: Some("execution-42".to_string()),
                execution_id: Some("managed-7".to_string()),
                ..ProcessEventQuery::default()
            })
            .unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].process_key, process_key(&process.identity));
        assert_eq!(events[0].execution_id.as_deref(), Some("managed-7"));
        assert!(
            store
                .query_process_events(&ProcessEventQuery {
                    limit: 10,
                    pid: Some(u32::MAX),
                    ..ProcessEventQuery::default()
                })
                .unwrap()
                .is_empty()
        );
    }

    #[test]
    fn preserves_managed_lineage_across_later_observations() {
        let directory = tempdir().unwrap();
        let store = Store::open(directory.path().join("state.sqlite3")).unwrap();
        let process = crate::process::process_info_for_pid(std::process::id()).unwrap();
        let controller = ProcessController::capture(true, Some("execution-42".to_string()));
        store
            .record_processes(
                std::slice::from_ref(&process),
                "execution.start",
                "result",
                None,
                &controller,
                "managed",
                Some("run-42"),
                &serde_json::json!({}),
            )
            .unwrap();
        store
            .record_processes(
                std::slice::from_ref(&process),
                "process.get",
                "observed",
                Some(&format!("pid:{}", process.identity.pid)),
                &controller,
                "observed",
                None,
                &serde_json::json!({}),
            )
            .unwrap();

        let dossier = store
            .process_dossier(&process_key(&process.identity), 10)
            .unwrap();
        assert_eq!(dossier.context.origin, "managed");
        assert_eq!(dossier.context.execution_id.as_deref(), Some("run-42"));
        assert_eq!(dossier.context.observations, 2);
    }

    #[test]
    fn deduplicates_unchanged_process_snapshots_in_the_causal_journal() {
        let directory = tempdir().unwrap();
        let store = Store::open(directory.path().join("state.sqlite3")).unwrap();
        let process = crate::process::process_info_for_pid(std::process::id()).unwrap();
        let controller = ProcessController::capture(true, Some("execution-42".to_string()));
        for _ in 0..10 {
            store
                .record_processes(
                    std::slice::from_ref(&process),
                    "process.get",
                    "observed",
                    None,
                    &controller,
                    "observed",
                    None,
                    &serde_json::json!({}),
                )
                .unwrap();
        }

        let connection = store.connection.lock().unwrap();
        let payloads = connection
            .query_row(
                "SELECT COUNT(*) FROM causal_payloads WHERE kind = 'process_snapshot'",
                [],
                |row| row.get::<_, i64>(0),
            )
            .unwrap();
        let events = connection
            .query_row("SELECT COUNT(*) FROM causal_events", [], |row| {
                row.get::<_, i64>(0)
            })
            .unwrap();
        assert_eq!(payloads, 1);
        assert_eq!(events, 10);
    }

    #[test]
    fn gives_one_active_owner_each_reservation_key() {
        let directory = tempdir().unwrap();
        let store = Store::open(directory.path().join("state.sqlite3")).unwrap();
        let first = Reservation {
            id: "reservation-1".to_string(),
            kind: ReservationKind::Port,
            key: "tcp/5173".to_string(),
            lease_id: "lease-1".to_string(),
            created_at: 1,
            expires_at: None,
            external_conflict: false,
            released: false,
        };
        let second = Reservation {
            id: "reservation-2".to_string(),
            lease_id: "lease-2".to_string(),
            ..first.clone()
        };

        store.acquire_reservation(&first).unwrap();
        let error = store.acquire_reservation(&second).unwrap_err();
        assert!(error.starts_with("RESERVATION_CONFLICT:"));
        store.release_reservation(&first.id).unwrap();
        store.acquire_reservation(&second).unwrap();
        assert_eq!(
            store.list_reservations(true).unwrap()[0].lease_id,
            "lease-2"
        );
    }

    #[test]
    fn keeps_causal_event_cursors_monotonic() {
        let directory = tempdir().unwrap();
        let store = Store::open(directory.path().join("state.sqlite3")).unwrap();
        for subject in ["process:1", "process:2"] {
            store
                .append_causal_event(CausalEvent {
                    sequence: 0,
                    id: uuid::Uuid::now_v7().to_string(),
                    at: now_ms(),
                    kind: "process.observed".to_string(),
                    subject: subject.to_string(),
                    actor: "test".to_string(),
                    correlation_id: "test-correlation".to_string(),
                    causation_id: None,
                    execution_id: None,
                    session_id: None,
                    payload_id: None,
                    details: serde_json::json!({}),
                })
                .unwrap();
        }
        let first = store.causal_events(0, 1).unwrap();
        let second = store.causal_events(first[0].sequence, 10).unwrap();
        assert_eq!(first.len(), 1);
        assert_eq!(second.len(), 1);
        assert!(second[0].sequence > first[0].sequence);
    }

    #[test]
    fn prunes_lru_payloads_to_a_size_cap_but_preserves_pins() {
        let directory = tempdir().unwrap();
        let store = Store::open(directory.path().join("state.sqlite3")).unwrap();
        let pinned = store
            .put_causal_payload("fixture", None, &serde_json::json!({ "value": "pinned" }))
            .unwrap();
        store.pin_causal_payload(&pinned.id, true).unwrap();
        let disposable = store
            .put_causal_payload(
                "fixture",
                None,
                &serde_json::json!({ "value": "disposable" }),
            )
            .unwrap();

        assert_eq!(store.prune_causal_payloads_to_size(0).unwrap(), 1);
        assert!(store.causal_payload(&pinned.id).unwrap().is_some());
        assert!(store.causal_payload(&disposable.id).unwrap().is_none());
    }
}