slabs-db 0.4.0

Low-level SQLite/SQLx raw-SQL battery with WAL tuning, explicit transactions, migrations, and schema.sql dump
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
//! Raw-SQL database library for Slabs.
//!
//! This crate owns the tuned `SQLite` WAL wrapper ([`Db`]), the optional `PostgreSQL` wrapper ([`PgDb`]),
//! URL engine detection ([`DbEngine`]), framework system schemas ([`SYSTEM_SCHEMA_SQL`], [`POSTGRES_SYSTEM_SCHEMA_SQL`]),
//! and FTS5 query escaping ([`fts5_query`]). It also re-exports [`QueryBuilder`] for dynamic parameterized SQL.
//!
//! # Owned types and system tables
//!
//! Calling [`Db::init_system_tables`], [`Db::migrate`], or [`Db::migrate_dir`] (and the matching [`PgDb`] methods)
//! creates these 12 framework tables if they do not exist:
//!
//! - `slabs_sessions`
//! - `slabs_magic_links`
//! - `slabs_access_tokens`
//! - `slabs_jobs`
//! - `slabs_cache`
//! - `slabs_mail_outbox`
//! - `slabs_blobs`
//! - `slabs_webhooks`
//! - `slabs_webhook_deliveries`
//! - `slabs_idempotency_keys`
//! - `slabs_audit_log`
//! - `slabs_incidents`
//!
//! # Invariants
//!
//! - **Split WAL pools on file-backed `SQLite`**: [`Db::reader`] returns a read-only pool with up to 16 connections for concurrent `SELECT` queries. [`Db::writer`] and [`Db::pool`] return a dedicated single-connection writer pool (`max_connections(1)`).
//! - **Explicit `BEGIN IMMEDIATE` transactions**: [`Db::begin`] opens a `BEGIN IMMEDIATE` transaction on the single writer pool. Use it for multi-step mutations so `SQLite` acquires the write lock up front and avoids `SQLITE_BUSY_SNAPSHOT` lock-upgrade failures.
//! - **In-memory test databases share one connection**: when `database_url` is `"sqlite::memory:"` or contains `"mode=memory"`, [`Db::connect`] clones the single writer pool for [`Db::reader`] because `SQLite` isolates in-memory databases per connection.
//! - **Tuned `SQLite` pragmas**: [`Db::connect`] sets `foreign_keys = ON`, `synchronous = NORMAL`, `cache_size = -64000`, `temp_store = MEMORY`, `trusted_schema = OFF`, `secure_delete = ON`, and `busy_timeout` (10s writer, 5s reader). File-backed databases also enable `journal_mode = WAL` and `mmap_size = 268435456` (256 MiB).
//! - **Parameterized SQL only**: always bind untrusted input with `sqlx::query`, `sqlx::query_as`, or [`QueryBuilder`]. Never interpolate user strings into SQL text.
//! - **FTS5 search escaping**: pass untrusted search strings through [`fts5_query`] before binding to an FTS5 `MATCH ?` clause. It strips double quotes and wraps each whitespace token as `"token"*` joined with `AND`.
//!
//! # Usage
//!
//! ```rust,no_run
//! use slabs_core::SlabResult;
//! use slabs_db::{fts5_query, Db};
//!
//! async fn example() -> SlabResult<()> {
//!     let db = Db::connect("sqlite://app.db?mode=rwc").await?;
//!     db.init_system_tables().await?;
//!
//!     // Concurrent SELECT on the read-only WAL pool.
//!     let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM slabs_jobs")
//!         .fetch_one(db.reader())
//!         .await?;
//!
//!     // Multi-step write inside an explicit BEGIN IMMEDIATE transaction.
//!     let mut tx = db.begin().await?;
//!     sqlx::query("DELETE FROM slabs_cache WHERE cache_key = ?")
//!         .bind("stale_key")
//!         .execute(&mut *tx)
//!         .await?;
//!     tx.commit().await?;
//!
//!     // Safe FTS5 query construction for user input.
//!     if let Some(match_expr) = fts5_query("deploy \"prod\"") {
//!         assert_eq!(match_expr, "\"deploy\"* AND \"prod\"*");
//!     }
//!     let _ = count;
//!     Ok(())
//! }
//! ```

use slabs_core::{SlabError, SlabResult};
use sqlx::{
    migrate::Migrator,
    postgres::PgPoolOptions,
    sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
    PgPool, Postgres, Sqlite, SqlitePool, Transaction,
};
use std::fmt::Write as _;
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;

pub use sqlx::QueryBuilder;

/// Database engine detected from a `DATABASE_URL` string.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DbEngine {
    /// Embedded `SQLite` database.
    Sqlite,
    /// Networked `PostgreSQL` database.
    Postgres,
}

impl DbEngine {
    /// Detects the [`DbEngine`] from a database connection URL.
    ///
    /// Returns [`DbEngine::Postgres`] when the trimmed, lowercased URL starts with
    /// `"postgres://"` or `"postgresql://"`, and [`DbEngine::Sqlite`] otherwise.
    #[must_use]
    pub fn detect(database_url: &str) -> Self {
        let lower = database_url.trim().to_ascii_lowercase();
        if lower.starts_with("postgres://") || lower.starts_with("postgresql://") {
            Self::Postgres
        } else {
            Self::Sqlite
        }
    }
}

/// Framework-owned `SQLite` DDL for the 12 system tables and their indexes.
///
/// Applied idempotently by [`Db::init_system_tables`], [`Db::migrate`], and [`Db::migrate_dir`].
pub const SYSTEM_SCHEMA_SQL: &str = r"
CREATE TABLE IF NOT EXISTS slabs_sessions (
    id TEXT PRIMARY KEY NOT NULL,
    user_id TEXT NOT NULL,
    role TEXT NOT NULL DEFAULT 'member',
    token_hash TEXT NOT NULL UNIQUE,
    expires_at TEXT NOT NULL,
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);

CREATE TABLE IF NOT EXISTS slabs_magic_links (
    id TEXT PRIMARY KEY NOT NULL,
    email TEXT NOT NULL,
    purpose TEXT NOT NULL DEFAULT 'sign_in',
    code_hash TEXT NOT NULL UNIQUE,
    expires_at TEXT NOT NULL,
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);

CREATE TABLE IF NOT EXISTS slabs_access_tokens (
    id TEXT PRIMARY KEY NOT NULL,
    user_id TEXT NOT NULL,
    role TEXT NOT NULL DEFAULT 'member',
    description TEXT NOT NULL DEFAULT '',
    permission TEXT NOT NULL DEFAULT 'write',
    token_hash TEXT NOT NULL UNIQUE,
    last_used_at TEXT,
    expires_at TEXT,
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);

CREATE TABLE IF NOT EXISTS slabs_jobs (
    id TEXT PRIMARY KEY NOT NULL,
    job_name TEXT NOT NULL,
    queue TEXT NOT NULL DEFAULT 'default',
    payload_json TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    attempts INTEGER NOT NULL DEFAULT 0,
    max_attempts INTEGER NOT NULL DEFAULT 5,
    run_at TEXT NOT NULL,
    locked_until TEXT,
    last_error TEXT,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);
CREATE INDEX IF NOT EXISTS idx_slabs_jobs_locked_until ON slabs_jobs(status, locked_until);

CREATE TABLE IF NOT EXISTS slabs_cache (
    cache_key TEXT PRIMARY KEY NOT NULL,
    value_text TEXT NOT NULL,
    expires_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);

CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
    id TEXT PRIMARY KEY NOT NULL,
    from_addr TEXT NOT NULL,
    to_addr TEXT NOT NULL,
    subject TEXT NOT NULL,
    text_body TEXT NOT NULL,
    html_body TEXT,
    sent_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS slabs_blobs (
    id TEXT PRIMARY KEY NOT NULL,
    filename TEXT NOT NULL,
    content_type TEXT NOT NULL,
    byte_size INTEGER NOT NULL,
    checksum_sha256 TEXT NOT NULL,
    storage_key TEXT NOT NULL UNIQUE,
    scope TEXT,
    created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS slabs_webhooks (
    id TEXT PRIMARY KEY NOT NULL,
    scope_id TEXT NOT NULL,
    name TEXT NOT NULL,
    url TEXT NOT NULL,
    signing_secret TEXT NOT NULL,
    subscribed_actions_json TEXT NOT NULL,
    active INTEGER NOT NULL DEFAULT 1,
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);

CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
    id TEXT PRIMARY KEY NOT NULL,
    webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
    action TEXT NOT NULL,
    payload_json TEXT NOT NULL,
    signature TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    response_status INTEGER,
    last_error TEXT,
    created_at TEXT NOT NULL,
    delivered_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);

CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
    scope TEXT NOT NULL,
    key TEXT NOT NULL,
    response_json TEXT,
    expires_at TEXT,
    created_at TEXT NOT NULL,
    PRIMARY KEY (scope, key)
);
CREATE INDEX IF NOT EXISTS idx_slabs_idempotency_keys_expires_at ON slabs_idempotency_keys(expires_at);

CREATE TABLE IF NOT EXISTS slabs_audit_log (
    id TEXT PRIMARY KEY NOT NULL,
    actor_id TEXT,
    action TEXT NOT NULL,
    target_type TEXT NOT NULL,
    target_id TEXT NOT NULL,
    metadata_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_id, created_at DESC);

CREATE TABLE IF NOT EXISTS slabs_incidents (
    id TEXT PRIMARY KEY,
    fingerprint TEXT NOT NULL UNIQUE,
    kind TEXT NOT NULL,
    source_file TEXT NOT NULL,
    route_pattern TEXT,
    status_code INTEGER,
    error_message TEXT NOT NULL,
    detail TEXT,
    context_json TEXT NOT NULL,
    git_sha TEXT,
    occurrences INTEGER NOT NULL DEFAULT 1,
    status TEXT NOT NULL DEFAULT 'open',
    resolved_in_sha TEXT,
    recent_occurrences_json TEXT NOT NULL DEFAULT '[]',
    first_seen_at TEXT NOT NULL,
    last_seen_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_incidents_status_seen
    ON slabs_incidents (status, last_seen_at DESC);
";

/// Framework-owned `PostgreSQL` DDL for the 12 system tables and their indexes.
///
/// Uses `TIMESTAMPTZ`, `JSONB`, `BIGINT`, and `BOOLEAN` column types.
/// Applied idempotently by [`PgDb::init_system_tables`], [`PgDb::migrate`], and [`PgDb::migrate_dir`].
pub const POSTGRES_SYSTEM_SCHEMA_SQL: &str = r"
CREATE TABLE IF NOT EXISTS slabs_sessions (
    id TEXT PRIMARY KEY NOT NULL,
    user_id TEXT NOT NULL,
    role TEXT NOT NULL DEFAULT 'member',
    token_hash TEXT NOT NULL UNIQUE,
    expires_at TIMESTAMPTZ NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);

CREATE TABLE IF NOT EXISTS slabs_magic_links (
    id TEXT PRIMARY KEY NOT NULL,
    email TEXT NOT NULL,
    purpose TEXT NOT NULL DEFAULT 'sign_in',
    code_hash TEXT NOT NULL UNIQUE,
    expires_at TIMESTAMPTZ NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);

CREATE TABLE IF NOT EXISTS slabs_access_tokens (
    id TEXT PRIMARY KEY NOT NULL,
    user_id TEXT NOT NULL,
    role TEXT NOT NULL DEFAULT 'member',
    description TEXT NOT NULL DEFAULT '',
    permission TEXT NOT NULL DEFAULT 'write',
    token_hash TEXT NOT NULL UNIQUE,
    last_used_at TIMESTAMPTZ,
    expires_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);

CREATE TABLE IF NOT EXISTS slabs_jobs (
    id TEXT PRIMARY KEY NOT NULL,
    job_name TEXT NOT NULL,
    queue TEXT NOT NULL DEFAULT 'default',
    payload_json JSONB NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    attempts BIGINT NOT NULL DEFAULT 0,
    max_attempts BIGINT NOT NULL DEFAULT 5,
    run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    locked_until TIMESTAMPTZ,
    last_error TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);
CREATE INDEX IF NOT EXISTS idx_slabs_jobs_locked_until ON slabs_jobs(status, locked_until);

CREATE TABLE IF NOT EXISTS slabs_cache (
    cache_key TEXT PRIMARY KEY NOT NULL,
    value_text TEXT NOT NULL,
    expires_at TIMESTAMPTZ NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);

CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
    id TEXT PRIMARY KEY NOT NULL,
    from_addr TEXT NOT NULL,
    to_addr TEXT NOT NULL,
    subject TEXT NOT NULL,
    text_body TEXT NOT NULL,
    html_body TEXT,
    sent_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS slabs_blobs (
    id TEXT PRIMARY KEY NOT NULL,
    filename TEXT NOT NULL,
    content_type TEXT NOT NULL,
    byte_size BIGINT NOT NULL,
    checksum_sha256 TEXT NOT NULL,
    storage_key TEXT NOT NULL UNIQUE,
    scope TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS slabs_webhooks (
    id TEXT PRIMARY KEY NOT NULL,
    scope_id TEXT NOT NULL,
    name TEXT NOT NULL,
    url TEXT NOT NULL,
    signing_secret TEXT NOT NULL,
    subscribed_actions_json JSONB NOT NULL,
    active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);

CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
    id TEXT PRIMARY KEY NOT NULL,
    webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
    action TEXT NOT NULL,
    payload_json JSONB NOT NULL,
    signature TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    response_status INTEGER,
    last_error TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    delivered_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);

CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
    scope TEXT NOT NULL,
    key TEXT NOT NULL,
    response_json TEXT,
    expires_at TIMESTAMPTZ,
    created_at TEXT NOT NULL,
    PRIMARY KEY (scope, key)
);
CREATE INDEX IF NOT EXISTS idx_slabs_idempotency_keys_expires_at ON slabs_idempotency_keys(expires_at);

CREATE TABLE IF NOT EXISTS slabs_audit_log (
    id TEXT PRIMARY KEY NOT NULL,
    actor_id TEXT,
    action TEXT NOT NULL,
    target_type TEXT NOT NULL,
    target_id TEXT NOT NULL,
    metadata_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_id, created_at DESC);

CREATE TABLE IF NOT EXISTS slabs_incidents (
    id TEXT PRIMARY KEY,
    fingerprint TEXT NOT NULL UNIQUE,
    kind TEXT NOT NULL,
    source_file TEXT NOT NULL,
    route_pattern TEXT,
    status_code INTEGER,
    error_message TEXT NOT NULL,
    detail TEXT,
    context_json TEXT NOT NULL,
    git_sha TEXT,
    occurrences INTEGER NOT NULL DEFAULT 1,
    status TEXT NOT NULL DEFAULT 'open',
    resolved_in_sha TEXT,
    recent_occurrences_json TEXT NOT NULL DEFAULT '[]',
    first_seen_at TEXT NOT NULL,
    last_seen_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_incidents_status_seen
    ON slabs_incidents (status, last_seen_at DESC);
";

/// Converts untrusted user search text into an FTS5 prefix-AND `MATCH` expression.
///
/// Splits on whitespace, strips `"` and ASCII control characters (including `\0`), caps
/// each token to 64 characters, keeps at most 16 tokens, wraps each remaining token as
/// `"token"*`, and joins them with `AND`.
/// Returns `None` when the input contains no non-empty tokens after sanitization.
#[must_use]
pub fn fts5_query(raw: &str) -> Option<String> {
    let terms: Vec<String> = raw
        .split_whitespace()
        .map(|tok| {
            tok.chars()
                .filter(|&ch| ch != '"' && !ch.is_ascii_control())
                .take(64)
                .collect::<String>()
        })
        .filter(|tok| !tok.is_empty())
        .take(16)
        .map(|tok| format!("\"{tok}\"*"))
        .collect();
    if terms.is_empty() {
        None
    } else {
        Some(terms.join(" AND "))
    }
}

/// Query parameters for cursor-based (keyset) pagination.
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct Pagination {
    /// Requested maximum number of items per page.
    pub limit: Option<u32>,
    /// Opaque cursor returned as `next_cursor` by the previous page.
    pub cursor: Option<String>,
}

impl Pagination {
    /// Resolves the page size, clamping it between `1` and `max_limit.max(1)`.
    ///
    /// Falls back to `default_limit` when [`Pagination::limit`] is `None`.
    #[must_use]
    pub fn clamped_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
        let upper = max_limit.max(1);
        let raw = self.limit.unwrap_or(default_limit);
        i64::from(raw.clamp(1, upper))
    }

    /// Returns `clamped_limit + 1` so callers can detect whether more rows exist without a `COUNT(*)`.
    #[must_use]
    pub fn fetch_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
        self.clamped_limit(default_limit, max_limit) + 1
    }
}

/// One page of cursor-paginated results.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CursorPage<T> {
    /// Items returned for the current page.
    pub items: Vec<T>,
    /// Cursor of the last item when more rows exist, or `None` on the final page.
    pub next_cursor: Option<String>,
    /// Whether additional rows exist beyond this page.
    pub has_more: bool,
}

impl<T> CursorPage<T> {
    /// Builds a [`CursorPage`] from rows fetched with `LIMIT (limit + 1)`.
    ///
    /// Truncates `rows` to `limit`, sets `has_more` when an extra row was present,
    /// and computes `next_cursor` from the last retained row via `cursor_fn`.
    #[must_use]
    pub fn from_rows(mut rows: Vec<T>, limit: usize, cursor_fn: impl Fn(&T) -> String) -> Self {
        let has_more = rows.len() > limit;
        if has_more {
            rows.truncate(limit);
        }
        let next_cursor = if has_more {
            rows.last().map(cursor_fn)
        } else {
            None
        };
        Self {
            items: rows,
            next_cursor,
            has_more,
        }
    }
}

/// Persisted audit event row stored in `slabs_audit_log`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
pub struct AuditEntry {
    /// Prefixed audit entry identifier (`aud_<ulid>`).
    pub id: String,
    /// Optional identifier of the user or service that performed the action.
    pub actor_id: Option<String>,
    /// Action name describing what happened (for example `"room.archived"`).
    pub action: String,
    /// Logical type of the affected resource (for example `"room"`).
    pub target_type: String,
    /// Identifier of the affected resource.
    pub target_id: String,
    /// JSON-serialized metadata payload attached to the audit event.
    pub metadata_json: String,
    /// RFC 3339 UTC timestamp when the audit entry was created.
    pub created_at: String,
}

/// Transactional audit log backed by the `slabs_audit_log` system table.
#[derive(Debug, Clone)]
pub struct AuditLog {
    db: Db,
}

impl AuditLog {
    /// Creates an [`AuditLog`] handle backed by `db`.
    #[must_use]
    pub fn new(db: Db) -> Self {
        Self { db }
    }

    /// Inserts an audit entry inside an open `SQLite` transaction so it commits or rolls back atomically.
    ///
    /// Returns the generated `aud_<ulid>` identifier.
    pub async fn record_in_tx(
        &self,
        tx: &mut Transaction<'_, Sqlite>,
        actor_id: Option<&str>,
        action: &str,
        target_type: &str,
        target_id: &str,
        metadata: &serde_json::Value,
    ) -> SlabResult<String> {
        let id = slabs_core::id::new("aud");
        let created_at = chrono::Utc::now().to_rfc3339();
        let metadata_json = serde_json::to_string(metadata)
            .map_err(|e| SlabError::internal(format!("failed to serialize audit metadata: {e}")))?;

        sqlx::query(
            "INSERT INTO slabs_audit_log (id, actor_id, action, target_type, target_id, metadata_json, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&id)
        .bind(actor_id)
        .bind(action)
        .bind(target_type)
        .bind(target_id)
        .bind(&metadata_json)
        .bind(&created_at)
        .execute(&mut **tx)
        .await?;

        Ok(id)
    }

    /// Lists up to `limit` (clamped to `1..=500`) most recent audit entries for a specific
    /// `(target_type, target_id)` on the read pool.
    pub async fn list_for_target(
        &self,
        target_type: &str,
        target_id: &str,
        limit: i64,
    ) -> SlabResult<Vec<AuditEntry>> {
        let limit = limit.clamp(1, 500);
        let rows: Vec<AuditEntry> = sqlx::query_as(
            "SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
             FROM slabs_audit_log
             WHERE target_type = ? AND target_id = ?
             ORDER BY created_at DESC, id DESC
             LIMIT ?",
        )
        .bind(target_type)
        .bind(target_id)
        .bind(limit)
        .fetch_all(self.db.reader())
        .await?;
        Ok(rows)
    }

    /// Lists up to `limit` (clamped to `1..=500`) most recent audit entries across all targets
    /// on the read pool.
    pub async fn list_recent(&self, limit: i64) -> SlabResult<Vec<AuditEntry>> {
        let limit = limit.clamp(1, 500);
        let rows: Vec<AuditEntry> = sqlx::query_as(
            "SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
             FROM slabs_audit_log
             ORDER BY created_at DESC, id DESC
             LIMIT ?",
        )
        .bind(limit)
        .fetch_all(self.db.reader())
        .await?;
        Ok(rows)
    }
}

const MAX_INCIDENT_ERROR_BYTES: usize = 1024;
const MAX_INCIDENT_DETAIL_BYTES: usize = 4096;
const MAX_RECENT_OCCURRENCES: usize = 10;

fn append_recent_occurrence(existing_json: &str, snapshot: serde_json::Value) -> String {
    let mut items =
        serde_json::from_str::<Vec<serde_json::Value>>(existing_json).unwrap_or_default();
    items.push(snapshot);
    if items.len() > MAX_RECENT_OCCURRENCES {
        let drain_count = items.len() - MAX_RECENT_OCCURRENCES;
        items.drain(..drain_count);
    }
    serde_json::to_string(&items).unwrap_or_else(|_| "[]".to_owned())
}

fn truncate_utf8(input: &str, max_bytes: usize) -> &str {
    if input.len() <= max_bytes {
        return input;
    }
    let mut end = max_bytes;
    while end > 0 && !input.is_char_boundary(end) {
        end -= 1;
    }
    &input[..end]
}

fn format_utc_micros(dt: chrono::DateTime<chrono::Utc>) -> String {
    dt.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)
}

/// Persisted runtime incident row stored in `slabs_incidents`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
pub struct IncidentRecord {
    /// Prefixed incident identifier (`inc_<ulid>`).
    pub id: String,
    /// Deterministic SHA-256 deduplication fingerprint.
    pub fingerprint: String,
    /// Incident category (for example `"panic"`, `"http_5xx"`, `"slow_request"`, `"job_dead"`, `"slow_job"`, or `"client_error"`).
    pub kind: String,
    /// Source file associated with the incident (for example `"slabs/rooms/send_message.rs"`, `"jobs/send_email.rs"`, or `"browser"`).
    pub source_file: String,
    /// Optional matched HTTP route pattern or job/browser path.
    pub route_pattern: Option<String>,
    /// Optional HTTP status code associated with the incident.
    pub status_code: Option<i64>,
    /// Truncated error summary (at most 1024 UTF-8 bytes).
    pub error_message: String,
    /// Optional extended diagnostic detail (at most 4096 UTF-8 bytes).
    pub detail: Option<String>,
    /// JSON-serialized redacted diagnostic context.
    pub context_json: String,
    /// Optional Git commit SHA active when the incident was last observed.
    pub git_sha: Option<String>,
    /// Number of times this fingerprinted incident has occurred.
    pub occurrences: i64,
    /// Lifecycle state (`"open"`, `"resolved"`, or `"reopened"`).
    pub status: String,
    /// Optional Git commit SHA recorded when the incident was resolved.
    pub resolved_in_sha: Option<String>,
    /// JSON array of the last 10 occurrence snapshots (`seen_at`, `git_sha`, `request_id`, `latency_ms`).
    pub recent_occurrences_json: String,
    /// Fixed-width UTC RFC 3339 timestamp when the incident was first recorded.
    pub first_seen_at: String,
    /// Fixed-width UTC RFC 3339 timestamp when the incident was most recently updated.
    pub last_seen_at: String,
}

/// Lifecycle outcome returned when recording an incident via [`Incidents::record_with_outcome`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum IncidentOutcome {
    /// A brand-new incident row was inserted.
    Opened,
    /// A previously resolved incident recurred and was transitioned to `"reopened"`.
    Reopened,
    /// An already-active (`"open"` or `"reopened"`) incident matched the fingerprint and had its occurrence count incremented.
    Incremented,
}

/// Input payload for recording a deduplicated runtime incident in `slabs_incidents`.
#[derive(Debug, Clone)]
pub struct IncidentInput {
    /// Incident category (for example `"panic"`, `"http_5xx"`, `"slow_request"`, `"job_dead"`, `"slow_job"`, `"client_error"`, or `"user_bug_report"`).
    pub kind: String,
    /// Source file owning the failing or slow code path.
    pub source_file: String,
    /// Optional matched HTTP route pattern or path.
    pub route_pattern: Option<String>,
    /// Optional HTTP status code.
    pub status_code: Option<i64>,
    /// Error or bottleneck summary (truncated to 1024 UTF-8 bytes on persistence).
    pub error_message: String,
    /// Optional extended diagnostic detail (truncated to 4096 UTF-8 bytes on persistence).
    pub detail: Option<String>,
    /// Redacted structured JSON context attached to the incident.
    pub context_json: serde_json::Value,
    /// Optional Git commit SHA active when the incident occurred.
    pub git_sha: Option<String>,
    /// Optional explicit deduplication fingerprint override.
    ///
    /// When `None`, the fingerprint is derived deterministically from `(kind, source_file,
    /// route_pattern, error_message)` — except for `"user_bug_report"`, which includes a unique
    /// nonce so each user bug report creates a distinct open record unless explicitly fingerprinted.
    pub custom_fingerprint: Option<String>,
}

/// Deduplicated runtime incident store backed by the `slabs_incidents` system table.
#[derive(Debug, Clone)]
pub struct Incidents {
    db: Db,
}

impl Incidents {
    /// Creates an [`Incidents`] handle backed by `db`.
    #[must_use]
    pub fn new(db: Db) -> Self {
        Self { db }
    }

    /// Atomically records or deduplicates an incident and returns its exact [`IncidentOutcome`].
    ///
    /// Uses `input.custom_fingerprint` when provided (hashed under a domain prefix so fingerprints
    /// remain fixed-width SHA-256 hex). Otherwise derives the fingerprint deterministically from
    /// `(kind, source_file, route_pattern, error_message)`, appending a unique nonce when
    /// `kind == "user_bug_report"` so individual user bug reports remain distinct.
    ///
    /// Truncates `error_message` to 1024 bytes and `detail` to 4096 bytes on UTF-8 character
    /// boundaries, and upserts inside a `BEGIN IMMEDIATE` transaction.
    pub async fn record_with_outcome(
        &self,
        input: IncidentInput,
    ) -> SlabResult<(IncidentRecord, IncidentOutcome)> {
        let fingerprint = if let Some(custom) = input
            .custom_fingerprint
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
        {
            slabs_core::fingerprint(&["custom", custom])
        } else if input.kind == "user_bug_report" {
            let nonce = slabs_core::id::new("bug");
            slabs_core::fingerprint(&[
                &input.kind,
                &input.source_file,
                input.route_pattern.as_deref().unwrap_or(""),
                &input.error_message,
                &nonce,
            ])
        } else {
            slabs_core::fingerprint(&[
                &input.kind,
                &input.source_file,
                input.route_pattern.as_deref().unwrap_or(""),
                &input.error_message,
            ])
        };
        let error_message =
            truncate_utf8(&input.error_message, MAX_INCIDENT_ERROR_BYTES).to_owned();
        let detail = input
            .detail
            .as_deref()
            .map(|d| truncate_utf8(d, MAX_INCIDENT_DETAIL_BYTES).to_owned());
        let context_json = serde_json::to_string(&input.context_json).map_err(|e| {
            SlabError::internal(format!("failed to serialize incident context: {e}"))
        })?;
        let now = format_utc_micros(chrono::Utc::now());
        let occurrence_snapshot = serde_json::json!({
            "seen_at": now,
            "git_sha": input.git_sha,
            "request_id": input.context_json.get("request_id"),
            "latency_ms": input.context_json.get("latency_ms"),
        });

        let mut tx = self.db.begin().await?;
        let existing: Option<IncidentRecord> = sqlx::query_as(
            "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
                    detail, context_json, git_sha, occurrences, status, resolved_in_sha,
                    recent_occurrences_json, first_seen_at, last_seen_at
             FROM slabs_incidents
             WHERE fingerprint = ?",
        )
        .bind(&fingerprint)
        .fetch_optional(&mut *tx)
        .await?;

        let (record, outcome) = if let Some(prev) = existing {
            let reopened = prev.status == "resolved";
            let next_status = if reopened {
                "reopened".to_owned()
            } else {
                prev.status.clone()
            };
            let next_resolved_in_sha = if reopened {
                None
            } else {
                prev.resolved_in_sha.clone()
            };
            let next_occurrences = prev.occurrences + 1;
            let next_recent_occurrences_json =
                append_recent_occurrence(&prev.recent_occurrences_json, occurrence_snapshot);

            sqlx::query(
                "UPDATE slabs_incidents
                 SET occurrences = ?,
                     last_seen_at = ?,
                     detail = ?,
                     context_json = ?,
                     git_sha = ?,
                     status = ?,
                     resolved_in_sha = ?,
                     recent_occurrences_json = ?
                 WHERE id = ?",
            )
            .bind(next_occurrences)
            .bind(&now)
            .bind(&detail)
            .bind(&context_json)
            .bind(&input.git_sha)
            .bind(&next_status)
            .bind(&next_resolved_in_sha)
            .bind(&next_recent_occurrences_json)
            .bind(&prev.id)
            .execute(&mut *tx)
            .await?;

            let updated = IncidentRecord {
                id: prev.id,
                fingerprint: prev.fingerprint,
                kind: prev.kind,
                source_file: prev.source_file,
                route_pattern: prev.route_pattern,
                status_code: prev.status_code,
                error_message: prev.error_message,
                detail,
                context_json,
                git_sha: input.git_sha,
                occurrences: next_occurrences,
                status: next_status,
                resolved_in_sha: next_resolved_in_sha,
                recent_occurrences_json: next_recent_occurrences_json,
                first_seen_at: prev.first_seen_at,
                last_seen_at: now,
            };
            let outcome = if reopened {
                IncidentOutcome::Reopened
            } else {
                IncidentOutcome::Incremented
            };
            (updated, outcome)
        } else {
            let id = slabs_core::id::new("inc");
            let recent_occurrences_json = append_recent_occurrence("[]", occurrence_snapshot);
            sqlx::query(
                "INSERT INTO slabs_incidents (
                     id, fingerprint, kind, source_file, route_pattern, status_code,
                     error_message, detail, context_json, git_sha, occurrences,
                     status, resolved_in_sha, recent_occurrences_json, first_seen_at, last_seen_at
                 )
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 'open', NULL, ?, ?, ?)",
            )
            .bind(&id)
            .bind(&fingerprint)
            .bind(&input.kind)
            .bind(&input.source_file)
            .bind(&input.route_pattern)
            .bind(input.status_code)
            .bind(&error_message)
            .bind(&detail)
            .bind(&context_json)
            .bind(&input.git_sha)
            .bind(&recent_occurrences_json)
            .bind(&now)
            .bind(&now)
            .execute(&mut *tx)
            .await?;

            let inserted = IncidentRecord {
                id,
                fingerprint,
                kind: input.kind,
                source_file: input.source_file,
                route_pattern: input.route_pattern,
                status_code: input.status_code,
                error_message,
                detail,
                context_json,
                git_sha: input.git_sha,
                occurrences: 1,
                status: "open".to_owned(),
                resolved_in_sha: None,
                recent_occurrences_json,
                first_seen_at: now.clone(),
                last_seen_at: now,
            };
            (inserted, IncidentOutcome::Opened)
        };

        tx.commit().await?;
        Ok((record, outcome))
    }

    /// Atomically records or deduplicates an incident by deterministic fingerprint.
    ///
    /// Delegates to [`Incidents::record_with_outcome`], returning `(record, is_new_or_reopened)`,
    /// where the boolean is `true` for [`IncidentOutcome::Opened`] or [`IncidentOutcome::Reopened`].
    pub async fn record(&self, input: IncidentInput) -> SlabResult<(IncidentRecord, bool)> {
        let (record, outcome) = self.record_with_outcome(input).await?;
        Ok((
            record,
            matches!(outcome, IncidentOutcome::Opened | IncidentOutcome::Reopened),
        ))
    }

    /// Lists up to `limit` (clamped to `1..=500`) incidents ordered by `last_seen_at DESC` on the read pool.
    ///
    /// - `None` or `Some("active")`: returns active incidents (`status IN ('open', 'reopened')`).
    /// - `Some("open")`, `Some("reopened")`, or `Some("resolved")`: returns exact status matches.
    /// - `Some("all")`: returns incidents across all lifecycle states.
    pub async fn list(&self, status: Option<&str>, limit: i64) -> SlabResult<Vec<IncidentRecord>> {
        let limit = limit.clamp(1, 500);
        let filter = status.map(str::trim).filter(|s| !s.is_empty());

        let rows: Vec<IncidentRecord> = match filter {
            None => {
                sqlx::query_as(
                    "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
                            detail, context_json, git_sha, occurrences, status, resolved_in_sha,
                            recent_occurrences_json, first_seen_at, last_seen_at
                     FROM slabs_incidents
                     WHERE status IN ('open', 'reopened')
                     ORDER BY last_seen_at DESC, id DESC
                     LIMIT ?",
                )
                .bind(limit)
                .fetch_all(self.db.reader())
                .await?
            }
            Some(st) if st.eq_ignore_ascii_case("active") => {
                sqlx::query_as(
                    "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
                            detail, context_json, git_sha, occurrences, status, resolved_in_sha,
                            recent_occurrences_json, first_seen_at, last_seen_at
                     FROM slabs_incidents
                     WHERE status IN ('open', 'reopened')
                     ORDER BY last_seen_at DESC, id DESC
                     LIMIT ?",
                )
                .bind(limit)
                .fetch_all(self.db.reader())
                .await?
            }
            Some(st) if st.eq_ignore_ascii_case("all") => {
                sqlx::query_as(
                    "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
                            detail, context_json, git_sha, occurrences, status, resolved_in_sha,
                            recent_occurrences_json, first_seen_at, last_seen_at
                     FROM slabs_incidents
                     ORDER BY last_seen_at DESC, id DESC
                     LIMIT ?",
                )
                .bind(limit)
                .fetch_all(self.db.reader())
                .await?
            }
            Some(st) => {
                sqlx::query_as(
                    "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
                            detail, context_json, git_sha, occurrences, status, resolved_in_sha,
                            recent_occurrences_json, first_seen_at, last_seen_at
                     FROM slabs_incidents
                     WHERE status = ?
                     ORDER BY last_seen_at DESC, id DESC
                     LIMIT ?",
                )
                .bind(st)
                .bind(limit)
                .fetch_all(self.db.reader())
                .await?
            }
        };
        Ok(rows)
    }

    /// Fetches a single incident by its `inc_<ulid>` identifier on the read pool.
    pub async fn get(&self, id: &str) -> SlabResult<Option<IncidentRecord>> {
        let row: Option<IncidentRecord> = sqlx::query_as(
            "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
                    detail, context_json, git_sha, occurrences, status, resolved_in_sha,
                    recent_occurrences_json, first_seen_at, last_seen_at
             FROM slabs_incidents
             WHERE id = ?",
        )
        .bind(id)
        .fetch_optional(self.db.reader())
        .await?;
        Ok(row)
    }

    /// Marks an incident as `"resolved"` with an optional `resolved_in_sha`, updating `last_seen_at`.
    ///
    /// Returns `true` if a matching row was updated, or `false` if `id` does not exist.
    pub async fn resolve(&self, id: &str, resolved_in_sha: Option<&str>) -> SlabResult<bool> {
        let now = format_utc_micros(chrono::Utc::now());
        let res = sqlx::query(
            "UPDATE slabs_incidents
             SET status = 'resolved',
                 resolved_in_sha = ?,
                 last_seen_at = ?
             WHERE id = ?",
        )
        .bind(resolved_in_sha)
        .bind(&now)
        .bind(id)
        .execute(self.db.writer())
        .await?;
        Ok(res.rows_affected() > 0)
    }

    /// Auto-resolves active (`"open"` or `"reopened"`) incidents whose `last_seen_at` is older
    /// than `stale_days` days, recording `resolved_in_sha = 'auto:stale'` when unset.
    ///
    /// Passing `0` disables auto-closing and returns `Ok(0)`. Returns the number of rows closed.
    pub async fn close_stale(&self, stale_days: u64) -> SlabResult<u64> {
        if stale_days == 0 {
            return Ok(0);
        }
        let days = i64::try_from(stale_days.min(3650)).unwrap_or(3650);
        let now_dt = chrono::Utc::now();
        let cutoff_dt = now_dt
            .checked_sub_signed(chrono::Duration::days(days))
            .ok_or_else(|| SlabError::internal("stale incident cutoff timestamp overflow"))?;
        let now = format_utc_micros(now_dt);
        let cutoff = format_utc_micros(cutoff_dt);
        let res = sqlx::query(
            "UPDATE slabs_incidents
             SET status = 'resolved',
                 resolved_in_sha = COALESCE(resolved_in_sha, 'auto:stale'),
                 last_seen_at = ?
             WHERE status IN ('open', 'reopened')
               AND last_seen_at < ?",
        )
        .bind(&now)
        .bind(&cutoff)
        .execute(self.db.writer())
        .await?;
        Ok(res.rows_affected())
    }

    /// Returns the number of currently active (`"open"` or `"reopened"`) incidents on the read pool.
    pub async fn count_open(&self) -> SlabResult<i64> {
        let (count,): (i64,) = sqlx::query_as(
            "SELECT COUNT(*) FROM slabs_incidents WHERE status IN ('open', 'reopened')",
        )
        .fetch_one(self.db.reader())
        .await?;
        Ok(count)
    }
}

/// Raw-SQL `SQLite` database wrapper tuned for concurrent WAL workloads.
///
/// Holds two pools on file-backed databases:
/// - A single-connection writer pool (`max_connections(1)`) used by [`Db::writer`], [`Db::pool`], and [`Db::begin`] (`BEGIN IMMEDIATE`).
/// - A 16-connection read-only pool used by [`Db::reader`] for parallel `SELECT` queries.
///
/// In-memory databases (`sqlite::memory:` or `mode=memory`) share the single writer pool for both reads and writes.
#[derive(Debug, Clone)]
pub struct Db {
    read_pool: SqlitePool,
    write_pool: SqlitePool,
}

impl Db {
    /// Connects to a `SQLite` database with tuned WAL pragmas and split read/write pools.
    ///
    /// Creates the database file when missing and enables `foreign_keys = ON`, `synchronous = NORMAL`,
    /// `cache_size = -64000`, and `temp_store = MEMORY`. File-backed databases also enable
    /// `journal_mode = WAL`, `mmap_size = 268435456`, and a separate 16-connection read-only pool.
    /// Returns [`SlabError::Internal`] if `database_url` cannot be parsed.
    pub async fn connect(database_url: &str) -> SlabResult<Self> {
        let is_memory = database_url == "sqlite::memory:" || database_url.contains("mode=memory");

        let mut write_opts = SqliteConnectOptions::from_str(database_url)
            .map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
            .create_if_missing(true)
            .foreign_keys(true)
            .busy_timeout(Duration::from_secs(10))
            .synchronous(SqliteSynchronous::Normal)
            .pragma("cache_size", "-64000")
            .pragma("temp_store", "MEMORY")
            .pragma("trusted_schema", "OFF")
            .pragma("secure_delete", "ON");

        if !is_memory {
            write_opts = write_opts
                .journal_mode(SqliteJournalMode::Wal)
                .pragma("mmap_size", "268435456");
        }

        // Single dedicated writer guarantees serialized writes without SQLITE_BUSY thrashing.
        let write_pool = SqlitePoolOptions::new()
            .max_connections(1)
            .acquire_timeout(Duration::from_secs(10))
            .connect_with(write_opts)
            .await?;

        let read_pool = if is_memory {
            // In-memory SQLite databases are per-connection, so share the single pool in tests.
            write_pool.clone()
        } else {
            let read_opts = SqliteConnectOptions::from_str(database_url)
                .map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
                .read_only(true)
                .foreign_keys(true)
                .busy_timeout(Duration::from_secs(5))
                .pragma("cache_size", "-64000")
                .pragma("temp_store", "MEMORY")
                .pragma("trusted_schema", "OFF")
                .pragma("mmap_size", "268435456");

            SqlitePoolOptions::new()
                .max_connections(16)
                .acquire_timeout(Duration::from_secs(5))
                .connect_with(read_opts)
                .await?
        };

        Ok(Self {
            read_pool,
            write_pool,
        })
    }

    /// Returns the default pool, which aliases the single-connection writer pool.
    ///
    /// Prefer [`Db::reader`] for read-only `SELECT` queries so reads run concurrently on file-backed databases.
    #[must_use]
    pub fn pool(&self) -> &SqlitePool {
        &self.write_pool
    }

    /// Returns the concurrent read-only WAL pool (up to 16 connections on file-backed databases).
    ///
    /// Use this pool for `SELECT` queries. Executing write statements on a file-backed reader pool fails.
    #[must_use]
    pub fn reader(&self) -> &SqlitePool {
        &self.read_pool
    }

    /// Returns the dedicated single-connection writer pool (`max_connections(1)`).
    ///
    /// Serializes writes in-process with a 10-second `busy_timeout` to prevent `SQLITE_BUSY` thrashing.
    #[must_use]
    pub fn writer(&self) -> &SqlitePool {
        &self.write_pool
    }

    /// Opens an explicit `BEGIN IMMEDIATE` transaction on the single writer connection.
    ///
    /// Acquires the write lock at transaction start, avoiding deferred lock-upgrade `SQLITE_BUSY_SNAPSHOT` errors.
    pub async fn begin(&self) -> SlabResult<Transaction<'_, Sqlite>> {
        Ok(self.write_pool.begin_with("BEGIN IMMEDIATE").await?)
    }

    /// Ensures an existing `SQLite` system table has `column` (adding it if absent).
    async fn ensure_sqlite_column(
        &self,
        table: &str,
        column: &str,
        column_def: &str,
    ) -> SlabResult<()> {
        let query = format!("SELECT name FROM pragma_table_info('{table}')");
        let cols: Vec<(String,)> = sqlx::query_as(&query).fetch_all(&self.write_pool).await?;
        if !cols.is_empty() && !cols.iter().any(|(name,)| name == column) {
            let alter = format!("ALTER TABLE {table} ADD COLUMN {column} {column_def}");
            sqlx::raw_sql(&alter).execute(&self.write_pool).await?;
        }
        Ok(())
    }

    /// Executes [`SYSTEM_SCHEMA_SQL`] against the writer pool to create all 12 system tables idempotently,
    /// upgrading legacy `slabs_jobs`, `slabs_idempotency_keys`, `slabs_blobs`, and `slabs_incidents`
    /// tables in place when needed.
    pub async fn init_system_tables(&self) -> SlabResult<()> {
        self.ensure_sqlite_column("slabs_jobs", "locked_until", "TEXT")
            .await?;
        self.ensure_sqlite_column("slabs_idempotency_keys", "expires_at", "TEXT")
            .await?;
        self.ensure_sqlite_column("slabs_blobs", "scope", "TEXT")
            .await?;
        self.ensure_sqlite_column(
            "slabs_incidents",
            "recent_occurrences_json",
            "TEXT NOT NULL DEFAULT '[]'",
        )
        .await?;
        sqlx::raw_sql(SYSTEM_SCHEMA_SQL)
            .execute(&self.write_pool)
            .await?;
        Ok(())
    }

    /// Creates system tables if missing and runs all pending migrations from `migrator` on the writer pool.
    ///
    /// Wraps migration failures in [`SlabError::Internal`].
    pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
        self.init_system_tables().await?;
        migrator
            .run(&self.write_pool)
            .await
            .map_err(|e| SlabError::internal(format!("migration failed: {e}")))?;
        Ok(())
    }

    /// Creates system tables if missing and runs all SQL migrations located in `dir` on the writer pool.
    ///
    /// Wraps directory load and migration failures in [`SlabError::Internal`].
    pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
        self.init_system_tables().await?;
        let migrator = Migrator::new(dir)
            .await
            .map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
        self.migrate(&migrator).await
    }

    /// Exports the current `SQLite` schema DDL from `sqlite_master` on the read pool.
    ///
    /// Excludes internal `sqlite_%` and `_sqlx_%` objects and orders statements by table, index, trigger, then view.
    pub async fn dump_schema_sql(&self) -> SlabResult<String> {
        let rows: Vec<(String, String, Option<String>)> = sqlx::query_as(
            "SELECT type, name, sql
             FROM sqlite_master
             WHERE sql IS NOT NULL
               AND name NOT LIKE 'sqlite_%'
               AND name NOT LIKE '_sqlx_%'
             ORDER BY
               CASE type
                 WHEN 'table' THEN 1
                 WHEN 'index' THEN 2
                 WHEN 'trigger' THEN 3
                 WHEN 'view' THEN 4
                 ELSE 5
               END,
               name ASC",
        )
        .fetch_all(&self.read_pool)
        .await?;

        let mut out = String::from(
            "-- Auto-generated by slabs-db (SQLite). Single-file schema truth for humans and agents.\n\n",
        );
        for (_kind, _name, sql) in rows {
            if let Some(stmt) = sql {
                out.push_str(stmt.trim());
                if !stmt.trim_end().ends_with(';') {
                    out.push(';');
                }
                out.push_str("\n\n");
            }
        }
        Ok(out)
    }

    /// Reads a `.sql` file from disk and executes its statements atomically inside a `SQLite` transaction.
    ///
    /// Intended for seed scripts such as `slabs db seed`. Empty or whitespace-only files are a no-op.
    pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
        let sql = std::fs::read_to_string(path).map_err(|e| {
            SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
        })?;
        if sql.trim().is_empty() {
            return Ok(());
        }
        let mut tx = self.begin().await?;
        sqlx::raw_sql(&sql).execute(&mut *tx).await?;
        tx.commit().await?;
        Ok(())
    }

    /// Executes `SELECT 1` against the read pool to verify database connectivity.
    pub async fn ping(&self) -> SlabResult<()> {
        let _: (i64,) = sqlx::query_as("SELECT 1")
            .fetch_one(&self.read_pool)
            .await?;
        Ok(())
    }

    /// Runs `PRAGMA wal_checkpoint(TRUNCATE)` on the writer pool and cleanly closes
    /// both the reader and writer connection pools.
    ///
    /// Logs a warning if the checkpoint fails rather than panicking so graceful
    /// shutdown always completes cleanly.
    pub async fn checkpoint_and_close(&self) {
        if let Err(err) = sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)")
            .execute(&self.write_pool)
            .await
        {
            tracing::warn!(error = %err, "SQLite WAL checkpoint failed during shutdown");
        }
        self.read_pool.close().await;
        self.write_pool.close().await;
    }

    /// Runs `SQLite` `EXPLAIN QUERY PLAN` for a single read-only `SELECT` or `WITH` statement
    /// against the read pool and returns each plan `detail` line.
    ///
    /// Rejects empty SQL, queries containing `;`, and statements not starting with `SELECT` or
    /// `WITH` (case-insensitive) with [`SlabError::BadRequest`].
    pub async fn explain_query_plan(&self, sql: &str) -> SlabResult<Vec<String>> {
        let trimmed = sql.trim();
        if trimmed.is_empty() {
            return Err(SlabError::bad_request("SQL query cannot be empty"));
        }
        if trimmed.contains(';') {
            return Err(SlabError::bad_request(
                "SQL query must be a single statement without semicolons",
            ));
        }

        let starts_select = trimmed.len() > 6
            && trimmed
                .get(..6)
                .is_some_and(|p| p.eq_ignore_ascii_case("SELECT"))
            && trimmed
                .as_bytes()
                .get(6)
                .is_some_and(u8::is_ascii_whitespace);
        let starts_with = trimmed.len() > 4
            && trimmed
                .get(..4)
                .is_some_and(|p| p.eq_ignore_ascii_case("WITH"))
            && trimmed
                .as_bytes()
                .get(4)
                .is_some_and(u8::is_ascii_whitespace);

        if !starts_select && !starts_with {
            return Err(SlabError::bad_request(
                "only read-only SELECT or WITH queries can be explained",
            ));
        }

        let explain_sql = format!("EXPLAIN QUERY PLAN {trimmed}");
        let rows: Vec<(i64, i64, i64, String)> = sqlx::query_as(&explain_sql)
            .fetch_all(self.reader())
            .await?;
        Ok(rows.into_iter().map(|(_, _, _, detail)| detail).collect())
    }
}

fn quote_pg_ident(ident: &str) -> String {
    format!("\"{}\"", ident.replace('"', "\"\""))
}

/// Raw-SQL `PostgreSQL` database wrapper for multi-node deployments.
#[derive(Debug, Clone)]
pub struct PgDb {
    pool: PgPool,
}

impl PgDb {
    /// Connects to a `PostgreSQL` database with up to 20 pooled connections, a 5-second acquire
    /// timeout, a 5-minute idle timeout, and a 30-minute maximum connection lifetime.
    pub async fn connect(database_url: &str) -> SlabResult<Self> {
        let pool = PgPoolOptions::new()
            .max_connections(20)
            .acquire_timeout(Duration::from_secs(5))
            .idle_timeout(Duration::from_secs(300))
            .max_lifetime(Duration::from_secs(1800))
            .connect(database_url)
            .await?;
        Ok(Self { pool })
    }

    /// Returns the underlying `sqlx` `PostgreSQL` connection pool.
    #[must_use]
    pub fn pool(&self) -> &PgPool {
        &self.pool
    }

    /// Begins a new `PostgreSQL` transaction on the pool.
    pub async fn begin(&self) -> SlabResult<Transaction<'_, Postgres>> {
        Ok(self.pool.begin().await?)
    }

    /// Executes [`POSTGRES_SYSTEM_SCHEMA_SQL`] to create all 12 system tables idempotently,
    /// upgrading legacy `slabs_jobs`, `slabs_idempotency_keys`, `slabs_blobs`, and `slabs_incidents`
    /// tables in place when needed.
    pub async fn init_system_tables(&self) -> SlabResult<()> {
        sqlx::raw_sql(
            "ALTER TABLE IF EXISTS slabs_jobs ADD COLUMN IF NOT EXISTS locked_until TIMESTAMPTZ;
             ALTER TABLE IF EXISTS slabs_idempotency_keys ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;
             ALTER TABLE IF EXISTS slabs_blobs ADD COLUMN IF NOT EXISTS scope TEXT;
             ALTER TABLE IF EXISTS slabs_incidents ADD COLUMN IF NOT EXISTS recent_occurrences_json TEXT NOT NULL DEFAULT '[]';",
        )
        .execute(&self.pool)
        .await?;
        sqlx::raw_sql(POSTGRES_SYSTEM_SCHEMA_SQL)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    /// Creates system tables if missing and runs all pending migrations from `migrator`.
    ///
    /// Wraps migration failures in [`SlabError::Internal`].
    pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
        self.init_system_tables().await?;
        migrator
            .run(&self.pool)
            .await
            .map_err(|e| SlabError::internal(format!("postgres migration failed: {e}")))?;
        Ok(())
    }

    /// Creates system tables if missing and runs all SQL migrations located in `dir`.
    ///
    /// Wraps directory load and migration failures in [`SlabError::Internal`].
    pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
        self.init_system_tables().await?;
        let migrator = Migrator::new(dir)
            .await
            .map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
        self.migrate(&migrator).await
    }

    /// Exports `public` schema tables and indexes from `information_schema.columns` and `pg_indexes`.
    ///
    /// Excludes `_sqlx_%` internal migration tables.
    pub async fn dump_schema_sql(&self) -> SlabResult<String> {
        let cols: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
            "SELECT table_name, column_name, data_type, is_nullable, column_default
             FROM information_schema.columns
             WHERE table_schema = 'public'
               AND table_name NOT LIKE '_sqlx_%'
             ORDER BY table_name ASC, ordinal_position ASC",
        )
        .fetch_all(&self.pool)
        .await?;

        let indexes: Vec<(String,)> = sqlx::query_as(
            "SELECT indexdef
             FROM pg_indexes
             WHERE schemaname = 'public'
               AND tablename NOT LIKE '_sqlx_%'
             ORDER BY tablename ASC, indexname ASC",
        )
        .fetch_all(&self.pool)
        .await?;

        let mut out = String::from(
            "-- Auto-generated by slabs-db (PostgreSQL). Single-file schema truth for humans and agents.\n\n",
        );

        let mut current_table: Option<String> = None;
        for (table, col, dtype, nullable, default) in cols {
            if current_table.as_deref() == Some(table.as_str()) {
                out.push_str(",\n");
            } else {
                if current_table.is_some() {
                    out.push_str(");\n\n");
                }
                let quoted_table = quote_pg_ident(&table);
                let _ = writeln!(out, "CREATE TABLE {quoted_table} (");
                current_table = Some(table);
            }
            let quoted_col = quote_pg_ident(&col);
            let _ = write!(out, "    {quoted_col} {dtype}");
            if nullable == "NO" {
                out.push_str(" NOT NULL");
            }
            if let Some(def) = default {
                let _ = write!(out, " DEFAULT {def}");
            }
        }
        if current_table.is_some() {
            out.push_str("\n);\n\n");
        }

        for (indexdef,) in indexes {
            out.push_str(&indexdef);
            if !indexdef.ends_with(';') {
                out.push(';');
            }
            out.push_str("\n\n");
        }

        Ok(out)
    }

    /// Reads a `.sql` file from disk and executes its statements against the `PostgreSQL` pool.
    ///
    /// Intended for seed scripts such as `slabs db seed`. Empty or whitespace-only files are a no-op.
    pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
        let sql = std::fs::read_to_string(path).map_err(|e| {
            SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
        })?;
        if sql.trim().is_empty() {
            return Ok(());
        }
        sqlx::raw_sql(&sql).execute(&self.pool).await?;
        Ok(())
    }

    /// Executes `SELECT 1` against the `PostgreSQL` pool to verify database connectivity.
    pub async fn ping(&self) -> SlabResult<()> {
        let _: (i32,) = sqlx::query_as("SELECT 1").fetch_one(&self.pool).await?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detects_sqlite_and_postgres_urls() {
        assert_eq!(DbEngine::detect("sqlite::memory:"), DbEngine::Sqlite);
        assert_eq!(
            DbEngine::detect("sqlite://app.db?mode=rwc"),
            DbEngine::Sqlite
        );
        assert_eq!(
            DbEngine::detect("postgres://user:pass@localhost:5432/slabs"),
            DbEngine::Postgres
        );
        assert_eq!(
            DbEngine::detect("postgresql://localhost/slabs"),
            DbEngine::Postgres
        );
    }

    #[test]
    fn fts5_query_safely_quotes_user_input() {
        assert_eq!(
            fts5_query(r#"hello "world" fts5"#),
            Some(r#""hello"* AND "world"* AND "fts5"*"#.to_string())
        );
        assert_eq!(fts5_query("   "), None);
    }

    #[tokio::test]
    async fn split_wal_pools_handle_concurrent_writers_and_readers_without_sqlite_busy() {
        let path =
            std::env::temp_dir().join(format!("slabs_wal_stress_{}.db", slabs_core::id::new("db")));
        let url = format!("sqlite://{}", path.display());
        let db = Db::connect(&url).await.unwrap();
        sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT NOT NULL)")
            .execute(db.writer())
            .await
            .unwrap();

        let mut handles = Vec::new();
        // 24 concurrent writers using BEGIN IMMEDIATE + 24 concurrent readers on WAL read_pool
        for i in 0..24 {
            let db_w = db.clone();
            handles.push(tokio::spawn(async move {
                let mut tx = db_w.begin().await.unwrap();
                sqlx::query("INSERT INTO items (val) VALUES (?)")
                    .bind(format!("item-{i}"))
                    .execute(&mut *tx)
                    .await
                    .unwrap();
                tx.commit().await.unwrap();
            }));

            let db_r = db.clone();
            handles.push(tokio::spawn(async move {
                let _count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
                    .fetch_one(db_r.reader())
                    .await
                    .unwrap();
            }));
        }

        for h in handles {
            h.await.unwrap();
        }

        let (total,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
            .fetch_one(db.reader())
            .await
            .unwrap();
        assert_eq!(total, 24);

        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(format!("{}-wal", path.display()));
        let _ = std::fs::remove_file(format!("{}-shm", path.display()));
    }

    #[test]
    fn pagination_clamps_limits_and_computes_fetch_limit() {
        let default_page = Pagination::default();
        assert_eq!(default_page.clamped_limit(20, 100), 20);
        assert_eq!(default_page.fetch_limit(20, 100), 21);

        let zero_page = Pagination {
            limit: Some(0),
            cursor: None,
        };
        assert_eq!(zero_page.clamped_limit(20, 100), 1);
        assert_eq!(zero_page.fetch_limit(20, 100), 2);

        let huge_page = Pagination {
            limit: Some(500),
            cursor: Some("cur_1".into()),
        };
        assert_eq!(huge_page.clamped_limit(20, 100), 100);
        assert_eq!(huge_page.fetch_limit(20, 100), 101);
        assert_eq!(huge_page.cursor.as_deref(), Some("cur_1"));
    }

    #[test]
    fn cursor_page_from_rows_truncates_and_sets_next_cursor() {
        let page = CursorPage::from_rows(vec![10, 20, 30], 2, ToString::to_string);
        assert_eq!(page.items, vec![10, 20]);
        assert!(page.has_more);
        assert_eq!(page.next_cursor.as_deref(), Some("20"));

        let exact = CursorPage::from_rows(vec![10, 20], 2, ToString::to_string);
        assert_eq!(exact.items, vec![10, 20]);
        assert!(!exact.has_more);
        assert!(exact.next_cursor.is_none());

        let empty = CursorPage::from_rows(Vec::<i32>::new(), 2, ToString::to_string);
        assert_eq!(empty.items, Vec::<i32>::new());
        assert!(!empty.has_more);
        assert!(empty.next_cursor.is_none());
    }

    #[tokio::test]
    async fn audit_log_commits_and_rolls_back_atomically_with_tx() {
        let db = Db::connect("sqlite::memory:").await.unwrap();
        db.init_system_tables().await.unwrap();
        let audit = AuditLog::new(db.clone());

        // Committed transaction persists audit entry
        let mut tx = db.begin().await.unwrap();
        let entry_id = audit
            .record_in_tx(
                &mut tx,
                Some("usr_1"),
                "room.created",
                "room",
                "room_1",
                &serde_json::json!({ "name": "Lobby" }),
            )
            .await
            .unwrap();
        assert!(entry_id.starts_with("aud_"));
        tx.commit().await.unwrap();

        // Rolled back transaction does not persist audit entry
        let mut rollback_tx = db.begin().await.unwrap();
        let _rolled_back_id = audit
            .record_in_tx(
                &mut rollback_tx,
                Some("usr_2"),
                "room.deleted",
                "room",
                "room_1",
                &serde_json::json!({ "reason": "rolled back" }),
            )
            .await
            .unwrap();
        rollback_tx.rollback().await.unwrap();

        // Second committed entry on another target to verify filtering
        let mut tx2 = db.begin().await.unwrap();
        let _other_id = audit
            .record_in_tx(
                &mut tx2,
                None,
                "user.invited",
                "user",
                "usr_9",
                &serde_json::json!({}),
            )
            .await
            .unwrap();
        tx2.commit().await.unwrap();

        let room_entries = audit.list_for_target("room", "room_1", 10).await.unwrap();
        assert_eq!(room_entries.len(), 1);
        assert_eq!(room_entries[0].id, entry_id);
        assert_eq!(room_entries[0].actor_id.as_deref(), Some("usr_1"));
        assert_eq!(room_entries[0].action, "room.created");
        assert_eq!(room_entries[0].target_type, "room");
        assert_eq!(room_entries[0].target_id, "room_1");
        assert_eq!(room_entries[0].metadata_json, r#"{"name":"Lobby"}"#);

        let recent = audit.list_recent(10).await.unwrap();
        assert_eq!(recent.len(), 2);

        let recent_limited = audit.list_recent(1).await.unwrap();
        assert_eq!(recent_limited.len(), 1);
    }

    #[tokio::test]
    async fn execute_sql_file_runs_seed_statements_and_handles_empty_or_missing() {
        let db = Db::connect("sqlite::memory:").await.unwrap();
        db.init_system_tables().await.unwrap();

        let seed_path = std::env::temp_dir().join(format!(
            "slabs_seed_test_{}.sql",
            slabs_core::id::new("sql")
        ));
        std::fs::write(
            &seed_path,
            "CREATE TABLE widgets (id TEXT PRIMARY KEY, name TEXT NOT NULL);\n\
             INSERT INTO widgets (id, name) VALUES ('w_1', 'Alpha');\n\
             INSERT INTO widgets (id, name) VALUES ('w_2', 'Beta');\n",
        )
        .unwrap();

        db.execute_sql_file(&seed_path).await.unwrap();
        let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM widgets")
            .fetch_one(db.reader())
            .await
            .unwrap();
        assert_eq!(count, 2);

        // Blank seed file is a no-op
        std::fs::write(&seed_path, "   \n\t  ").unwrap();
        db.execute_sql_file(&seed_path).await.unwrap();
        let _ = std::fs::remove_file(&seed_path);

        // Missing file returns an internal error
        let missing = std::env::temp_dir().join("slabs_definitely_missing_seed.sql");
        assert!(db.execute_sql_file(&missing).await.is_err());

        // Both system schemas declare the new v0.2.0 system tables
        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
    }

    #[test]
    fn fts5_query_strips_control_chars_and_caps_tokens_and_lengths() {
        assert_eq!(
            fts5_query("hello\x00world \x07foo\x7fbar"),
            Some("\"helloworld\"* AND \"foobar\"*".to_string())
        );
        assert_eq!(fts5_query("\0\x01\x1f\x7f"), None);

        // Cap at 16 tokens
        let many_tokens = (1..=25)
            .map(|i| format!("tok{i}"))
            .collect::<Vec<_>>()
            .join(" ");
        let rendered = fts5_query(&many_tokens).unwrap();
        assert_eq!(rendered.split(" AND ").count(), 16);
        assert!(rendered.contains("\"tok16\"*"));
        assert!(!rendered.contains("\"tok17\"*"));

        // Cap each token to 64 chars
        let huge_token = "a".repeat(100);
        let rendered_long = fts5_query(&huge_token).unwrap();
        assert_eq!(rendered_long, format!("\"{}\"*", "a".repeat(64)));
    }

    #[tokio::test]
    async fn init_system_tables_adds_locked_until_and_expires_at_and_upgrades_legacy_tables() {
        let db = Db::connect("sqlite::memory:").await.unwrap();

        // Simulate legacy v0.2.0 tables without locked_until / expires_at
        sqlx::raw_sql(
            "CREATE TABLE slabs_jobs (
                id TEXT PRIMARY KEY NOT NULL,
                job_name TEXT NOT NULL,
                queue TEXT NOT NULL DEFAULT 'default',
                payload_json TEXT NOT NULL,
                status TEXT NOT NULL DEFAULT 'pending',
                attempts INTEGER NOT NULL DEFAULT 0,
                max_attempts INTEGER NOT NULL DEFAULT 5,
                run_at TEXT NOT NULL,
                last_error TEXT,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            );
            CREATE TABLE slabs_idempotency_keys (
                scope TEXT NOT NULL,
                key TEXT NOT NULL,
                response_json TEXT,
                created_at TEXT NOT NULL,
                PRIMARY KEY (scope, key)
            );
            CREATE TABLE slabs_blobs (
                id TEXT PRIMARY KEY NOT NULL,
                filename TEXT NOT NULL,
                content_type TEXT NOT NULL,
                byte_size INTEGER NOT NULL,
                checksum_sha256 TEXT NOT NULL,
                storage_key TEXT NOT NULL UNIQUE,
                created_at TEXT NOT NULL
            );
            CREATE TABLE slabs_incidents (
                id TEXT PRIMARY KEY,
                fingerprint TEXT NOT NULL UNIQUE,
                kind TEXT NOT NULL,
                source_file TEXT NOT NULL,
                route_pattern TEXT,
                status_code INTEGER,
                error_message TEXT NOT NULL,
                detail TEXT,
                context_json TEXT NOT NULL,
                git_sha TEXT,
                occurrences INTEGER NOT NULL DEFAULT 1,
                status TEXT NOT NULL DEFAULT 'open',
                resolved_in_sha TEXT,
                first_seen_at TEXT NOT NULL,
                last_seen_at TEXT NOT NULL
            );",
        )
        .execute(db.writer())
        .await
        .unwrap();

        // Running init_system_tables twice should upgrade once and stay idempotent
        db.init_system_tables().await.unwrap();
        db.init_system_tables().await.unwrap();

        let job_cols: Vec<(String,)> =
            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_jobs')")
                .fetch_all(db.reader())
                .await
                .unwrap();
        assert!(job_cols.iter().any(|(c,)| c == "locked_until"));

        let idem_cols: Vec<(String,)> =
            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_idempotency_keys')")
                .fetch_all(db.reader())
                .await
                .unwrap();
        assert!(idem_cols.iter().any(|(c,)| c == "expires_at"));

        let blob_cols: Vec<(String,)> =
            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_blobs')")
                .fetch_all(db.reader())
                .await
                .unwrap();
        assert!(blob_cols.iter().any(|(c,)| c == "scope"));
        assert!(SYSTEM_SCHEMA_SQL.contains("scope TEXT"));
        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("scope TEXT"));

        let incident_cols: Vec<(String,)> =
            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_incidents')")
                .fetch_all(db.reader())
                .await
                .unwrap();
        assert!(
            incident_cols
                .iter()
                .any(|(c,)| c == "recent_occurrences_json"),
            "missing upgraded column recent_occurrences_json"
        );
        assert!(SYSTEM_SCHEMA_SQL.contains("recent_occurrences_json"));
        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("recent_occurrences_json"));
        for removed in ["assignee", "external_issue_key", "external_issue_url"] {
            assert!(!SYSTEM_SCHEMA_SQL.contains(removed));
            assert!(!POSTGRES_SYSTEM_SCHEMA_SQL.contains(removed));
        }

        // Verify security pragmas
        let (trusted_schema,): (i64,) = sqlx::query_as("PRAGMA trusted_schema")
            .fetch_one(db.writer())
            .await
            .unwrap();
        assert_eq!(trusted_schema, 0);

        let (secure_delete,): (i64,) = sqlx::query_as("PRAGMA secure_delete")
            .fetch_one(db.writer())
            .await
            .unwrap();
        assert_eq!(secure_delete, 1);
    }

    #[tokio::test]
    async fn audit_log_clamps_limits_to_1_through_500() {
        let db = Db::connect("sqlite::memory:").await.unwrap();
        db.init_system_tables().await.unwrap();
        let audit = AuditLog::new(db.clone());

        let mut tx = db.begin().await.unwrap();
        for i in 0..3 {
            audit
                .record_in_tx(
                    &mut tx,
                    Some("usr_1"),
                    "item.updated",
                    "item",
                    "item_1",
                    &serde_json::json!({ "n": i }),
                )
                .await
                .unwrap();
        }
        tx.commit().await.unwrap();

        // Non-positive limits clamp up to 1 (never SQLite's unlimited -1)
        assert_eq!(audit.list_recent(-1).await.unwrap().len(), 1);
        assert_eq!(audit.list_recent(0).await.unwrap().len(), 1);
        assert_eq!(
            audit
                .list_for_target("item", "item_1", -5)
                .await
                .unwrap()
                .len(),
            1
        );
        assert_eq!(
            audit
                .list_for_target("item", "item_1", 0)
                .await
                .unwrap()
                .len(),
            1
        );
        // Huge limit clamps to 500 and still succeeds
        assert_eq!(audit.list_recent(10_000).await.unwrap().len(), 3);
    }

    #[tokio::test]
    async fn execute_sql_file_rolls_back_on_error() {
        let db = Db::connect("sqlite::memory:").await.unwrap();
        sqlx::query("CREATE TABLE items (id TEXT PRIMARY KEY)")
            .execute(db.writer())
            .await
            .unwrap();

        let seed_path = std::env::temp_dir().join(format!(
            "slabs_seed_rollback_{}.sql",
            slabs_core::id::new("sql")
        ));
        std::fs::write(
            &seed_path,
            "INSERT INTO items (id) VALUES ('ok_1');\n\
             INSERT INTO items (id) VALUES ('ok_1');\n",
        )
        .unwrap();

        assert!(db.execute_sql_file(&seed_path).await.is_err());
        let _ = std::fs::remove_file(&seed_path);

        let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
            .fetch_one(db.reader())
            .await
            .unwrap();
        assert_eq!(count, 0);
    }

    #[test]
    fn quote_pg_ident_escapes_double_quotes() {
        assert_eq!(quote_pg_ident("users"), "\"users\"");
        assert_eq!(quote_pg_ident("weird\"name"), "\"weird\"\"name\"");
    }

    #[tokio::test]
    async fn incidents_record_deduplicate_list_get_resolve_and_reopen() {
        let db = Db::connect("sqlite::memory:").await.unwrap();
        db.init_system_tables().await.unwrap();
        let incidents = Incidents::new(db.clone());

        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_incidents"));
        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_incidents"));

        // Multibyte UTF-8 strings exceeding limits truncate cleanly on char boundaries
        let long_msg = "é".repeat(700); // 1400 bytes > 1024
        let long_detail = "€".repeat(2000); // 6000 bytes > 4096

        let input = IncidentInput {
            kind: "panic".into(),
            source_file: "slabs/rooms/send_message.rs".into(),
            route_pattern: Some("/api/rooms/{room_id}/messages".into()),
            status_code: Some(500),
            error_message: long_msg.clone(),
            detail: Some(long_detail),
            context_json: serde_json::json!({ "request_id": "req_1" }),
            git_sha: Some("sha_aaa".into()),
            custom_fingerprint: None,
        };

        let (first, is_new) = incidents.record(input.clone()).await.unwrap();
        assert!(is_new);
        assert!(first.id.starts_with("inc_"));
        assert_eq!(first.occurrences, 1);
        assert_eq!(first.status, "open");
        assert!(first.error_message.len() <= MAX_INCIDENT_ERROR_BYTES);
        assert!(first.detail.as_deref().unwrap().len() <= MAX_INCIDENT_DETAIL_BYTES);
        assert_eq!(incidents.count_open().await.unwrap(), 1);

        // Second identical incident deduplicates and increments occurrences
        let mut second_input = input.clone();
        second_input.detail = Some("updated detail".into());
        second_input.git_sha = Some("sha_bbb".into());
        let (second, is_new_second) = incidents.record(second_input).await.unwrap();
        assert!(!is_new_second);
        assert_eq!(second.id, first.id);
        assert_eq!(second.occurrences, 2);
        assert_eq!(second.status, "open");
        assert_eq!(second.detail.as_deref(), Some("updated detail"));
        assert_eq!(second.git_sha.as_deref(), Some("sha_bbb"));

        // Fetch by id
        let fetched = incidents.get(&first.id).await.unwrap().unwrap();
        assert_eq!(fetched.id, first.id);
        assert_eq!(fetched.occurrences, 2);
        assert!(incidents.get("inc_missing").await.unwrap().is_none());

        // Resolve incident
        assert!(incidents.resolve(&first.id, Some("sha_fix")).await.unwrap());
        assert!(!incidents.resolve("inc_missing", None).await.unwrap());
        assert_eq!(incidents.count_open().await.unwrap(), 0);
        assert!(incidents.list(Some("open"), 10).await.unwrap().is_empty());
        let resolved_list = incidents.list(Some("resolved"), 10).await.unwrap();
        assert_eq!(resolved_list.len(), 1);
        assert_eq!(resolved_list[0].resolved_in_sha.as_deref(), Some("sha_fix"));

        // Re-occurring resolved incident transitions to "reopened" and returns is_new = true
        let (reopened, is_reopened) = incidents.record(input.clone()).await.unwrap();
        assert!(is_reopened);
        assert_eq!(reopened.id, first.id);
        assert_eq!(reopened.status, "reopened");
        assert_eq!(reopened.occurrences, 3);
        assert!(reopened.resolved_in_sha.is_none());
        assert_eq!(incidents.count_open().await.unwrap(), 1);

        // Another occurrence while "reopened" keeps status "reopened" and returns is_new = false
        let (still_reopened, is_new_again) = incidents.record(input).await.unwrap();
        assert!(!is_new_again);
        assert_eq!(still_reopened.status, "reopened");
        assert_eq!(still_reopened.occurrences, 4);

        // Listing with None / "active" / "reopened" / "all" filters accurately and clamps limits
        assert_eq!(incidents.list(None, -1).await.unwrap().len(), 1);
        assert_eq!(incidents.list(Some("active"), 10).await.unwrap().len(), 1);
        assert_eq!(incidents.list(Some("reopened"), 10).await.unwrap().len(), 1);
        assert!(incidents.list(Some("open"), 10).await.unwrap().is_empty());
        assert_eq!(incidents.list(Some("all"), 999).await.unwrap().len(), 1);

        // Resolving a "reopened" incident transitions back to "resolved"
        assert!(incidents
            .resolve(&first.id, Some("sha_fix_2"))
            .await
            .unwrap());
        assert_eq!(incidents.count_open().await.unwrap(), 0);
        assert!(incidents.list(Some("active"), 10).await.unwrap().is_empty());
        assert!(incidents.list(None, 10).await.unwrap().is_empty());
        assert_eq!(incidents.list(Some("resolved"), 10).await.unwrap().len(), 1);
        assert_eq!(incidents.list(Some("all"), 10).await.unwrap().len(), 1);
    }

    #[tokio::test]
    async fn incidents_record_with_outcome_lifecycle_and_user_bug_reports() {
        let db = Db::connect("sqlite::memory:").await.unwrap();
        db.init_system_tables().await.unwrap();
        let incidents = Incidents::new(db);

        let base = IncidentInput {
            kind: "http_5xx".into(),
            source_file: "slabs/rooms/show.rs".into(),
            route_pattern: Some("/rooms/{id}".into()),
            status_code: Some(500),
            error_message: "boom".into(),
            detail: None,
            context_json: serde_json::json!({}),
            git_sha: Some("sha_1".into()),
            custom_fingerprint: None,
        };

        let (rec1, outcome1) = incidents.record_with_outcome(base.clone()).await.unwrap();
        assert_eq!(outcome1, IncidentOutcome::Opened);
        assert_eq!(rec1.status, "open");
        assert_eq!(rec1.occurrences, 1);

        let (rec2, outcome2) = incidents.record_with_outcome(base.clone()).await.unwrap();
        assert_eq!(outcome2, IncidentOutcome::Incremented);
        assert_eq!(rec2.id, rec1.id);
        assert_eq!(rec2.status, "open");
        assert_eq!(rec2.occurrences, 2);

        assert!(incidents.resolve(&rec1.id, Some("sha_fix")).await.unwrap());
        let (rec3, outcome3) = incidents.record_with_outcome(base.clone()).await.unwrap();
        assert_eq!(outcome3, IncidentOutcome::Reopened);
        assert_eq!(rec3.id, rec1.id);
        assert_eq!(rec3.status, "reopened");
        assert_eq!(rec3.occurrences, 3);
        assert!(rec3.resolved_in_sha.is_none());

        let (rec4, outcome4) = incidents.record_with_outcome(base).await.unwrap();
        assert_eq!(outcome4, IncidentOutcome::Incremented);
        assert_eq!(rec4.status, "reopened");
        assert_eq!(rec4.occurrences, 4);

        assert!(incidents.resolve(&rec1.id, Some("sha_fix2")).await.unwrap());
        let resolved_row = incidents.get(&rec1.id).await.unwrap().unwrap();
        assert_eq!(resolved_row.status, "resolved");
        assert_eq!(resolved_row.resolved_in_sha.as_deref(), Some("sha_fix2"));

        // User bug reports without custom_fingerprint create distinct open incidents
        let bug = IncidentInput {
            kind: "user_bug_report".into(),
            source_file: "slabs/rooms/show.rs".into(),
            route_pattern: Some("/rooms/1".into()),
            status_code: None,
            error_message: "Button does not respond".into(),
            detail: Some("Button does not respond".into()),
            context_json: serde_json::json!({ "reporter_user_id": "usr_1" }),
            git_sha: None,
            custom_fingerprint: None,
        };
        let (bug1, first_bug_outcome) = incidents.record_with_outcome(bug.clone()).await.unwrap();
        let (bug2, second_bug_outcome) = incidents.record_with_outcome(bug).await.unwrap();
        assert_eq!(first_bug_outcome, IncidentOutcome::Opened);
        assert_eq!(second_bug_outcome, IncidentOutcome::Opened);
        assert_ne!(bug1.id, bug2.id);

        // Explicit custom_fingerprint deduplicates deterministically when reused
        let mut custom = IncidentInput {
            kind: "user_bug_report".into(),
            source_file: "slabs/rooms/show.rs".into(),
            route_pattern: None,
            status_code: None,
            error_message: "Grouped bug".into(),
            detail: None,
            context_json: serde_json::json!({}),
            git_sha: None,
            custom_fingerprint: Some("bug_group_key".into()),
        };
        let (c1, grouped_first) = incidents.record_with_outcome(custom.clone()).await.unwrap();
        let (c2, grouped_second) = incidents.record_with_outcome(custom.clone()).await.unwrap();
        assert_eq!(grouped_first, IncidentOutcome::Opened);
        assert_eq!(grouped_second, IncidentOutcome::Incremented);
        assert_eq!(c1.id, c2.id);
        assert_eq!(c2.occurrences, 2);

        custom.custom_fingerprint = Some(slabs_core::id::new("bug"));
        let (c3, unique_custom) = incidents.record_with_outcome(custom).await.unwrap();
        assert_eq!(unique_custom, IncidentOutcome::Opened);
        assert_ne!(c3.id, c1.id);
    }

    #[tokio::test]
    async fn explain_query_plan_detects_scan_vs_index_and_rejects_non_select_sql() {
        let db = Db::connect("sqlite::memory:").await.unwrap();
        sqlx::raw_sql(
            "CREATE TABLE messages (
                id TEXT PRIMARY KEY NOT NULL,
                room_id TEXT NOT NULL,
                body TEXT NOT NULL
            );
            CREATE INDEX idx_messages_room ON messages(room_id);",
        )
        .execute(db.writer())
        .await
        .unwrap();

        // Unindexed filter -> full table SCAN
        let scan_plan = db
            .explain_query_plan("SELECT id FROM messages WHERE body = 'hello'")
            .await
            .unwrap();
        assert!(
            scan_plan.iter().any(|line| line.contains("SCAN messages")),
            "expected SCAN in plan: {scan_plan:?}"
        );

        // Indexed filter -> SEARCH ... USING INDEX
        let index_plan = db
            .explain_query_plan("SELECT id FROM messages WHERE room_id = 'room_1'")
            .await
            .unwrap();
        assert!(
            index_plan
                .iter()
                .any(|line| line.contains("USING INDEX idx_messages_room")
                    || line.contains("USING COVERING INDEX idx_messages_room")),
            "expected USING INDEX in plan: {index_plan:?}"
        );

        // CTE WITH query is permitted
        let cte_plan = db
            .explain_query_plan(
                "WITH r AS (SELECT id FROM messages WHERE room_id = 'r1') SELECT id FROM r",
            )
            .await
            .unwrap();
        assert!(
            cte_plan
                .iter()
                .any(|line| line.contains("idx_messages_room")),
            "expected idx_messages_room in CTE plan: {cte_plan:?}"
        );

        // Reject empty, semicolons, and non-SELECT statements
        assert!(db.explain_query_plan("   ").await.is_err());
        assert!(db
            .explain_query_plan("SELECT 1; DROP TABLE messages")
            .await
            .is_err());
        assert!(db.explain_query_plan("DELETE FROM messages").await.is_err());
        assert!(db
            .explain_query_plan("UPDATE messages SET body = 'x'")
            .await
            .is_err());
        assert!(db
            .explain_query_plan("INSERT INTO messages VALUES ('1','r','b')")
            .await
            .is_err());
        assert!(db.explain_query_plan("DROP TABLE messages").await.is_err());
        assert!(db
            .explain_query_plan("PRAGMA table_info(messages)")
            .await
            .is_err());
    }

    #[tokio::test]
    async fn incidents_ring_buffer_active_filtering_and_close_stale() {
        let db = Db::connect("sqlite::memory:").await.unwrap();
        db.init_system_tables().await.unwrap();
        let incidents = Incidents::new(db.clone());

        // Record 12 occurrences of the same fingerprinted incident; ring buffer keeps last 10
        let mut inc_id = String::new();
        for idx in 1..=12 {
            let input = IncidentInput {
                kind: "http_5xx".into(),
                source_file: "slabs/orders/charge.rs".into(),
                route_pattern: Some("/api/orders/charge".into()),
                status_code: Some(500),
                error_message: "gateway timeout".into(),
                detail: Some(format!("attempt {idx}")),
                context_json: serde_json::json!({
                    "request_id": format!("req_{idx}"),
                    "latency_ms": idx * 100,
                }),
                git_sha: Some(format!("sha_{idx:02}")),
                custom_fingerprint: None,
            };
            let (rec, outcome) = incidents.record_with_outcome(input).await.unwrap();
            if idx == 1 {
                assert_eq!(outcome, IncidentOutcome::Opened);
                inc_id = rec.id.clone();
            } else {
                assert_eq!(outcome, IncidentOutcome::Incremented);
            }
            if idx == 12 {
                let history: Vec<serde_json::Value> =
                    serde_json::from_str(&rec.recent_occurrences_json).unwrap();
                assert_eq!(history.len(), 10);
                assert_eq!(history[0]["git_sha"], "sha_03");
                assert_eq!(history[0]["request_id"], "req_3");
                assert_eq!(history[0]["latency_ms"], 300);
                assert_eq!(history[9]["git_sha"], "sha_12");
                assert_eq!(history[9]["request_id"], "req_12");
                assert_eq!(history[9]["latency_ms"], 1200);
                assert!(history[9]["seen_at"].as_str().is_some());
            }
        }

        // Resolve then recur -> transitions to "reopened" and clears resolved_in_sha
        assert!(incidents.resolve(&inc_id, Some("sha_fix")).await.unwrap());
        let recur_input = IncidentInput {
            kind: "http_5xx".into(),
            source_file: "slabs/orders/charge.rs".into(),
            route_pattern: Some("/api/orders/charge".into()),
            status_code: Some(500),
            error_message: "gateway timeout".into(),
            detail: None,
            context_json: serde_json::json!({ "request_id": "req_13", "latency_ms": 1300 }),
            git_sha: Some("sha_13".into()),
            custom_fingerprint: None,
        };
        let (reopened, outcome) = incidents
            .record_with_outcome(recur_input.clone())
            .await
            .unwrap();
        assert_eq!(outcome, IncidentOutcome::Reopened);
        assert_eq!(reopened.status, "reopened");
        assert!(reopened.resolved_in_sha.is_none());

        // Add a second fresh "open" incident so active = 1 open + 1 reopened = 2
        let fresh_input = IncidentInput {
            kind: "slow_request".into(),
            source_file: "slabs/orders/list.rs".into(),
            route_pattern: Some("/api/orders".into()),
            status_code: Some(200),
            error_message: "slow query".into(),
            detail: None,
            context_json: serde_json::json!({ "latency_ms": 900 }),
            git_sha: Some("sha_13".into()),
            custom_fingerprint: None,
        };
        let (fresh, fresh_outcome) = incidents.record_with_outcome(fresh_input).await.unwrap();
        assert_eq!(fresh_outcome, IncidentOutcome::Opened);

        assert_eq!(incidents.count_open().await.unwrap(), 2);
        assert_eq!(incidents.list(Some("active"), 10).await.unwrap().len(), 2);
        assert_eq!(incidents.list(None, 10).await.unwrap().len(), 2);
        assert_eq!(incidents.list(Some("open"), 10).await.unwrap().len(), 1);
        assert_eq!(incidents.list(Some("reopened"), 10).await.unwrap().len(), 1);

        // Age the reopened incident past 30 days (45 days old)
        let old_ts = format_utc_micros(chrono::Utc::now() - chrono::Duration::days(45));
        sqlx::query("UPDATE slabs_incidents SET last_seen_at = ? WHERE id = ?")
            .bind(&old_ts)
            .bind(&inc_id)
            .execute(db.writer())
            .await
            .unwrap();

        // close_stale(0) is a no-op
        assert_eq!(incidents.close_stale(0).await.unwrap(), 0);
        assert_eq!(incidents.count_open().await.unwrap(), 2);

        // close_stale(30) auto-resolves only the stale incident and stamps 'auto:stale'
        assert_eq!(incidents.close_stale(30).await.unwrap(), 1);
        assert_eq!(incidents.count_open().await.unwrap(), 1);
        let stale_closed = incidents.get(&inc_id).await.unwrap().unwrap();
        assert_eq!(stale_closed.status, "resolved");
        assert_eq!(stale_closed.resolved_in_sha.as_deref(), Some("auto:stale"));
        let still_fresh = incidents.get(&fresh.id).await.unwrap().unwrap();
        assert_eq!(still_fresh.status, "open");

        // If the stale-closed incident recurs, it transitions to "reopened" with resolved_in_sha cleared
        let (reopened_after_stale, outcome_after_stale) =
            incidents.record_with_outcome(recur_input).await.unwrap();
        assert_eq!(outcome_after_stale, IncidentOutcome::Reopened);
        assert_eq!(reopened_after_stale.status, "reopened");
        assert!(reopened_after_stale.resolved_in_sha.is_none());
        assert_eq!(incidents.count_open().await.unwrap(), 2);
    }

    #[tokio::test]
    async fn db_checkpoint_and_close_flushes_wal_and_closes_pools() {
        let path = std::env::temp_dir().join(format!(
            "slabs_checkpoint_close_{}.db",
            slabs_core::id::new("db")
        ));
        let url = format!("sqlite://{}", path.display());
        let db = Db::connect(&url).await.unwrap();
        db.init_system_tables().await.unwrap();

        let mut tx = db.begin().await.unwrap();
        sqlx::query("CREATE TABLE notes (id TEXT PRIMARY KEY, body TEXT NOT NULL)")
            .execute(&mut *tx)
            .await
            .unwrap();
        sqlx::query("INSERT INTO notes (id, body) VALUES ('n_1', 'hello wal')")
            .execute(&mut *tx)
            .await
            .unwrap();
        tx.commit().await.unwrap();

        // Exercise reader pool before shutdown
        let (before,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM notes")
            .fetch_one(db.reader())
            .await
            .unwrap();
        assert_eq!(before, 1);

        db.checkpoint_and_close().await;
        assert!(db.reader().is_closed());
        assert!(db.pool().is_closed());

        // Re-open the database file and verify data is durably persisted
        let reopened = Db::connect(&url).await.unwrap();
        let (body,): (String,) = sqlx::query_as("SELECT body FROM notes WHERE id = 'n_1'")
            .fetch_one(reopened.reader())
            .await
            .unwrap();
        assert_eq!(body, "hello wal");
        reopened.checkpoint_and_close().await;

        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(format!("{}-wal", path.display()));
        let _ = std::fs::remove_file(format!("{}-shm", path.display()));
    }
}