ccd-cli 1.0.0-beta.3

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

use anyhow::{bail, Result};
use rusqlite::Connection;

pub(crate) const CURRENT_VERSION: u32 = 16;
const TELEMETRY_COST_TABLE: &str = "telemetry_cost";
const LEGACY_TELEMETRY_IDENTITY_COLUMNS: &[&[&str]] = &[
    &["ccd", "_id"],
    &["github", "_issue_number"],
    &["backlog", "_provider"],
    &["backlog", "_kind"],
    &["backlog", "_id"],
    &["backlog", "_url"],
];

pub(crate) fn initialize(conn: &Connection, _pods_root: Option<&Path>) -> Result<()> {
    // Fresh init does NOT run gate (b). During M4(c) the pod-scoped code
    // paths are still live — `ccd session open --pod <name>` and similar
    // surfaces legitimately create `.ccd/pods/<pod>/` during normal
    // operation, so blocking their first state.db open would break
    // operator workflow. The gate's authoritative firing point is the
    // v15→v16 migration (`migrate_v15_to_v16_with_pods_root`), which is
    // where the RFC 0006 M4(c) plan anchors the invariant ("running
    // `ccd migrate from-pod-layout` once before the schema migration can
    // proceed"). The `_pods_root` parameter is retained so later
    // milestones can tighten this path once the pod-scoped surfaces are
    // fully retired; a review finding documenting the fresh-init gap
    // lives in the ccd#593 follow-ups.
    conn.execute_batch(SCHEMA_CURRENT)?;
    conn.pragma_update(None, "user_version", CURRENT_VERSION)?;
    Ok(())
}

pub(crate) fn migrate(conn: &Connection, pods_root: Option<&Path>) -> Result<()> {
    let version: u32 = conn.pragma_query_value(None, "user_version", |row| row.get(0))?;
    if version == CURRENT_VERSION {
        return Ok(());
    }
    if version > CURRENT_VERSION {
        bail!(
            "state.db schema version {version} is newer than supported ({CURRENT_VERSION}); \
             upgrade the ccd CLI"
        );
    }
    if version == 0 {
        // Run gate (b) BEFORE any DDL so a refused migration leaves the DB
        // byte-for-byte untouched. `repair_zero_version_schema` also
        // re-checks after SCHEMA_CURRENT to cover partial-schema recovery
        // (pre-existing memory_evidence with 'pod' in CHECK), but the
        // unconditional pre-flight here is what keeps the v0 path
        // atomic on the fail-closed path.
        if let Some(pods_root) = pods_root {
            check_pod_layer_collapse_gate_b(pods_root)?;
        }
        conn.execute_batch(SCHEMA_CURRENT)?;
        repair_zero_version_schema(conn, pods_root)?;
        conn.pragma_update(None, "user_version", CURRENT_VERSION)?;
        return Ok(());
    } else if version < 2 {
        migrate_v1_to_v2(conn)?;
    }
    if version < 3 {
        migrate_v2_to_v3(conn)?;
    }
    if version < 4 {
        migrate_v3_to_v4(conn)?;
    }
    if version < 5 {
        migrate_v4_to_v5(conn)?;
    }
    if version < 6 {
        migrate_v5_to_v6(conn)?;
    }
    if version < 7 {
        migrate_v6_to_v7(conn)?;
    }
    if version < 8 {
        migrate_v7_to_v8(conn)?;
    }
    if version < 9 {
        migrate_v8_to_v9(conn)?;
    }
    if version < 10 {
        migrate_v9_to_v10(conn)?;
    }
    if version < 11 {
        migrate_v10_to_v11(conn)?;
    }
    if version < 12 {
        migrate_v11_to_v12(conn)?;
    }
    if version < 13 {
        migrate_v12_to_v13(conn)?;
    }
    if version < 14 {
        migrate_v13_to_v14(conn)?;
    }
    if version < 15 {
        migrate_v14_to_v15(conn)?;
    }
    if version < 16 {
        migrate_v15_to_v16_with_pods_root(conn, pods_root)?;
    }
    conn.pragma_update(None, "user_version", CURRENT_VERSION)?;
    Ok(())
}

fn repair_zero_version_schema(conn: &Connection, pods_root: Option<&Path>) -> Result<()> {
    // A touched or partially-initialized DB can report user_version=0 even if
    // one or more tables already exist with an older shape. `CREATE TABLE IF
    // NOT EXISTS` restores missing tables but does not add missing columns, so
    // run targeted repair migrations for any known additive deltas.
    if !table_has_column(conn, "session", "mode")? {
        migrate_v3_to_v4(conn)?;
    }
    if !table_has_column(conn, TELEMETRY_COST_TABLE, "next_step_key")? {
        migrate_v4_to_v5(conn)?;
        migrate_v9_to_v10(conn)?;
    }
    if !table_has_column(conn, "session", "revision")? {
        migrate_v5_to_v6(conn)?;
    }
    if !table_has_column(conn, "handoff", "revision")?
        || !table_has_column(conn, "execution_gates", "revision")?
    {
        migrate_v6_to_v7(conn)?;
    }
    if !table_exists(conn, "memory_op_queue")? {
        migrate_v8_to_v9(conn)?;
    }
    if table_has_column(conn, TELEMETRY_COST_TABLE, "focus_key")? {
        migrate_v9_to_v10(conn)?;
    }
    if !table_has_column(conn, "projection_metadata", "session_id")? {
        migrate_v10_to_v11(conn)?;
    }
    if !table_exists(conn, "memory_evidence")? {
        migrate_v11_to_v12(conn)?;
    }
    if !table_exists(conn, "host_loop_events")? {
        migrate_v12_to_v13(conn)?;
    }
    if !table_exists(conn, "projection_cache_entries")?
        || !table_exists(conn, "projection_cache_events")?
        || !table_exists(conn, "work_stream_decay")?
    {
        migrate_v13_to_v14(conn)?;
    }
    if has_legacy_telemetry_identity(conn)? {
        migrate_v14_to_v15(conn)?;
    }
    if memory_evidence_check_allows_pod(conn)? {
        // Existing pre-collapse memory_evidence table survived the repair
        // — route through the full v15→v16 migration, which runs both gates
        // and rebuilds the table.
        migrate_v15_to_v16_with_pods_root(conn, pods_root)?;
    } else if let Some(pods_root) = pods_root {
        // SCHEMA_CURRENT already created the v16 memory_evidence shape (or
        // the table was never present), so gate (a) is vacuous. Gate (b)
        // still has to fire: the post-collapse invariant is environment-wide,
        // and a touched/partial DB must not let an operator skip past
        // unmigrated pods just because the CHECK enum happens to look clean.
        check_pod_layer_collapse_gate_b(pods_root)?;
    }
    Ok(())
}

fn is_safe_sql_identifier(ident: &str) -> bool {
    let mut chars = ident.chars();
    match chars.next() {
        Some(c) if c == '_' || c.is_ascii_alphabetic() => {}
        _ => return false,
    }
    chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
}

fn table_has_column(conn: &Connection, table: &str, column: &str) -> Result<bool> {
    if !is_safe_sql_identifier(table) {
        bail!("invalid SQL identifier for table: {table:?}");
    }
    let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
    let mut rows = stmt.query([])?;
    while let Some(row) = rows.next()? {
        if row.get::<_, String>(1)? == column {
            return Ok(true);
        }
    }
    Ok(false)
}

fn table_exists(conn: &Connection, table: &str) -> Result<bool> {
    let count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?1",
        [table],
        |row| row.get(0),
    )?;
    Ok(count > 0)
}

fn legacy_telemetry_column(parts: &[&str]) -> String {
    parts.concat()
}

fn has_legacy_telemetry_identity(conn: &Connection) -> Result<bool> {
    for column in LEGACY_TELEMETRY_IDENTITY_COLUMNS {
        if table_has_column(conn, TELEMETRY_COST_TABLE, &legacy_telemetry_column(column))? {
            return Ok(true);
        }
    }
    Ok(false)
}

fn legacy_telemetry_identity_column_defs() -> String {
    [
        format!(
            "    {} INTEGER NOT NULL DEFAULT 0,",
            legacy_telemetry_column(LEGACY_TELEMETRY_IDENTITY_COLUMNS[0])
        ),
        format!(
            "    {} INTEGER NOT NULL DEFAULT 0,",
            legacy_telemetry_column(LEGACY_TELEMETRY_IDENTITY_COLUMNS[1])
        ),
        format!(
            "    {} TEXT,",
            legacy_telemetry_column(LEGACY_TELEMETRY_IDENTITY_COLUMNS[2])
        ),
        format!(
            "    {} TEXT,",
            legacy_telemetry_column(LEGACY_TELEMETRY_IDENTITY_COLUMNS[3])
        ),
        format!(
            "    {} TEXT,",
            legacy_telemetry_column(LEGACY_TELEMETRY_IDENTITY_COLUMNS[4])
        ),
        format!(
            "    {} TEXT,",
            legacy_telemetry_column(LEGACY_TELEMETRY_IDENTITY_COLUMNS[5])
        ),
    ]
    .join("\n")
}

const SCHEMA_CURRENT: &str = r#"
CREATE TABLE IF NOT EXISTS handoff (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    title TEXT NOT NULL DEFAULT '',
    immediate_actions TEXT NOT NULL DEFAULT '[]',
    completed_state TEXT NOT NULL DEFAULT '[]',
    operational_guardrails TEXT NOT NULL DEFAULT '[]',
    key_files TEXT NOT NULL DEFAULT '[]',
    definition_of_done TEXT NOT NULL DEFAULT '[]',
    revision INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE IF NOT EXISTS session (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 4,
    started_at_epoch_s INTEGER NOT NULL,
    last_started_at_epoch_s INTEGER NOT NULL,
    start_count INTEGER NOT NULL DEFAULT 1,
    session_id TEXT,
    mode TEXT NOT NULL DEFAULT 'general' CHECK (mode IN ('general', 'research', 'implement')),
    owner_kind TEXT CHECK (owner_kind IN ('interactive', 'runtime_supervisor', 'runtime_worker')),
    owner_id TEXT,
    supervisor_id TEXT,
    lease_ttl_secs INTEGER,
    last_heartbeat_at_epoch_s INTEGER,
    revision INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE IF NOT EXISTS session_activity (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    session_id TEXT NOT NULL,
    actor_id TEXT NOT NULL,
    current_activity TEXT NOT NULL,
    updated_at_epoch_s INTEGER NOT NULL,
    session_revision INTEGER NOT NULL
);

CREATE TABLE IF NOT EXISTS escalation (
    id TEXT PRIMARY KEY,
    kind TEXT NOT NULL CHECK (kind IN ('blocking', 'non_blocking')),
    reason TEXT NOT NULL,
    created_at_epoch_s INTEGER NOT NULL,
    session_id TEXT
);

CREATE TABLE IF NOT EXISTS recovery (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    checkpoint_origin TEXT,
    checkpoint_captured_at_epoch_s INTEGER,
    checkpoint_session_started_at_epoch_s INTEGER,
    checkpoint_summary TEXT,
    checkpoint_immediate_actions TEXT,
    checkpoint_key_files TEXT,
    buffer_origin TEXT,
    buffer_captured_at_epoch_s INTEGER,
    buffer_session_started_at_epoch_s INTEGER,
    buffer_summary_lines TEXT
);

CREATE TABLE IF NOT EXISTS projection_metadata (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    source_fingerprint TEXT NOT NULL,
    projection_digests TEXT,
    tool_surface_fingerprint TEXT,
    session_id TEXT
);

CREATE TABLE IF NOT EXISTS execution_gates (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 2,
    seeded_from TEXT,
    gates TEXT NOT NULL DEFAULT '[]',
    revision INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE IF NOT EXISTS telemetry_cost (
    session_id TEXT PRIMARY KEY,
    recorded_at_epoch_s INTEGER NOT NULL,
    next_step_key TEXT NOT NULL DEFAULT '',
    next_step_title TEXT,
    model TEXT,
    session_cost_usd REAL NOT NULL,
    input_tokens INTEGER NOT NULL DEFAULT 0,
    output_tokens INTEGER NOT NULL DEFAULT 0,
    cache_creation_input_tokens INTEGER NOT NULL DEFAULT 0,
    cache_read_input_tokens INTEGER NOT NULL DEFAULT 0,
    blended_total_tokens INTEGER
);

CREATE INDEX IF NOT EXISTS telemetry_cost_next_step_key_idx
    ON telemetry_cost (next_step_key);

CREATE TABLE IF NOT EXISTS host_loop_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    session_id TEXT,
    host TEXT NOT NULL,
    hook TEXT NOT NULL,
    status TEXT NOT NULL,
    session_boundary_action TEXT,
    source_fingerprint TEXT,
    normalized_payload_hash TEXT,
    payload_chars INTEGER,
    payload_estimated_tokens INTEGER,
    host_total_context_chars INTEGER,
    overhead_ratio REAL,
    session_started_at_epoch_s INTEGER,
    session_last_started_at_epoch_s INTEGER,
    session_start_count INTEGER,
    section_metrics_json TEXT
);

CREATE INDEX IF NOT EXISTS host_loop_events_observed_idx
    ON host_loop_events (observed_at_epoch_s DESC);

CREATE INDEX IF NOT EXISTS host_loop_events_host_hook_idx
    ON host_loop_events (host, hook, observed_at_epoch_s DESC);

CREATE TABLE IF NOT EXISTS projection_cache_entries (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    target TEXT NOT NULL CHECK (target IN ('default', 'planning', 'session')),
    format TEXT NOT NULL CHECK (format IN ('narrative', 'symbolic', 'bundle')),
    source_fingerprint TEXT NOT NULL,
    tool_surface_fingerprint TEXT NOT NULL DEFAULT '',
    payload_json TEXT NOT NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS projection_cache_entries_key_idx
    ON projection_cache_entries (target, format, source_fingerprint, tool_surface_fingerprint);

CREATE INDEX IF NOT EXISTS projection_cache_entries_observed_idx
    ON projection_cache_entries (observed_at_epoch_s DESC);

CREATE TABLE IF NOT EXISTS projection_cache_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    session_id TEXT,
    target TEXT NOT NULL CHECK (target IN ('default', 'planning', 'session')),
    format TEXT NOT NULL CHECK (format IN ('narrative', 'symbolic', 'bundle')),
    source_fingerprint TEXT NOT NULL,
    tool_surface_fingerprint TEXT NOT NULL DEFAULT '',
    cache_status TEXT NOT NULL CHECK (cache_status IN ('hit', 'miss'))
);

CREATE INDEX IF NOT EXISTS projection_cache_events_target_format_idx
    ON projection_cache_events (target, format, observed_at_epoch_s DESC);

CREATE INDEX IF NOT EXISTS projection_cache_events_session_idx
    ON projection_cache_events (session_id, observed_at_epoch_s DESC);

CREATE TABLE IF NOT EXISTS work_stream_decay (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    session_id TEXT NOT NULL,
    consecutive_no_progress INTEGER NOT NULL DEFAULT 0,
    last_outcome TEXT NOT NULL CHECK (last_outcome IN ('progress', 'no_progress', 'neutral')),
    updated_at_epoch_s INTEGER NOT NULL,
    last_progress_at_epoch_s INTEGER
);

CREATE TABLE IF NOT EXISTS memory_op_queue (
    id TEXT PRIMARY KEY,
    command TEXT NOT NULL,
    request_fingerprint TEXT NOT NULL,
    plan_json TEXT NOT NULL,
    staged_at_epoch_s INTEGER NOT NULL,
    updated_at_epoch_s INTEGER NOT NULL,
    actor_id TEXT,
    session_id TEXT,
    reconciled INTEGER NOT NULL DEFAULT 0,
    outcome TEXT,
    authored_entry_ids TEXT NOT NULL DEFAULT '[]',
    authored_target_path TEXT,
    authored_source_path TEXT,
    snapshot_json TEXT
);

CREATE TABLE IF NOT EXISTS memory_evidence (
    id TEXT PRIMARY KEY,
    scope TEXT NOT NULL CHECK (scope IN ('workspace', 'work_stream', 'project', 'profile', 'project_truth')),
    entry_type TEXT NOT NULL CHECK (entry_type IN ('rule', 'constraint', 'heuristic', 'observation', 'attempt')),
    source_kind TEXT NOT NULL CHECK (source_kind IN ('transcript', 'session', 'event_stream', 'hook_output', 'log', 'document')),
    summary TEXT NOT NULL,
    summary_digest TEXT NOT NULL,
    observed_at_epoch_s INTEGER NOT NULL,
    actor_id TEXT,
    session_id TEXT,
    source_ref TEXT,
    host TEXT,
    host_hook TEXT,
    host_session_id TEXT,
    host_run_id TEXT,
    host_task_id TEXT,
    provider_name TEXT,
    provider_ref TEXT,
    extracted INTEGER NOT NULL DEFAULT 0,
    extracted_candidate_id TEXT,
    extracted_at_epoch_s INTEGER
);

CREATE INDEX IF NOT EXISTS memory_evidence_extracted_idx
    ON memory_evidence (extracted, observed_at_epoch_s);
"#;

fn migrate_v1_to_v2(conn: &Connection) -> Result<()> {
    conn.execute_batch(
        r#"
DROP TABLE IF EXISTS handoff_v2;

CREATE TABLE handoff_v2 (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    title TEXT NOT NULL DEFAULT '',
    immediate_actions TEXT NOT NULL DEFAULT '[]',
    completed_state TEXT NOT NULL DEFAULT '[]',
    operational_guardrails TEXT NOT NULL DEFAULT '[]',
    key_files TEXT NOT NULL DEFAULT '[]',
    definition_of_done TEXT NOT NULL DEFAULT '[]'
);

INSERT INTO handoff_v2
    (id, schema_version, title, immediate_actions, completed_state,
     operational_guardrails, key_files, definition_of_done)
SELECT
    id, schema_version, title, immediate_actions, completed_state,
    operational_guardrails, key_files, definition_of_done
FROM handoff;

DROP TABLE handoff;
ALTER TABLE handoff_v2 RENAME TO handoff;
"#,
    )?;
    Ok(())
}

fn migrate_v2_to_v3(conn: &Connection) -> Result<()> {
    conn.execute_batch(
        r#"
CREATE TABLE IF NOT EXISTS execution_gates (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    seeded_from TEXT,
    gates TEXT NOT NULL DEFAULT '[]'
);
"#,
    )?;
    Ok(())
}

fn migrate_v3_to_v4(conn: &Connection) -> Result<()> {
    conn.execute_batch(
        r#"
ALTER TABLE session
    ADD COLUMN mode TEXT NOT NULL DEFAULT 'general'
    CHECK (mode IN ('general', 'research', 'implement'));
"#,
    )?;
    Ok(())
}

fn migrate_v4_to_v5(conn: &Connection) -> Result<()> {
    conn.execute_batch(&format!(
        r#"
CREATE TABLE IF NOT EXISTS telemetry_cost (
    session_id TEXT PRIMARY KEY,
    recorded_at_epoch_s INTEGER NOT NULL,
    focus_key TEXT NOT NULL DEFAULT '',
    focus_title TEXT,
{legacy_identity_columns}
    model TEXT,
    session_cost_usd REAL NOT NULL,
    input_tokens INTEGER NOT NULL DEFAULT 0,
    output_tokens INTEGER NOT NULL DEFAULT 0,
    cache_creation_input_tokens INTEGER NOT NULL DEFAULT 0,
    cache_read_input_tokens INTEGER NOT NULL DEFAULT 0,
    blended_total_tokens INTEGER
);

CREATE INDEX IF NOT EXISTS telemetry_cost_focus_key_idx
    ON telemetry_cost (focus_key);
"#,
        legacy_identity_columns = legacy_telemetry_identity_column_defs()
    ))?;
    Ok(())
}

fn migrate_v5_to_v6(conn: &Connection) -> Result<()> {
    conn.execute_batch(
        r#"
ALTER TABLE session
    ADD COLUMN owner_kind TEXT
    CHECK (owner_kind IN ('interactive', 'runtime_supervisor', 'runtime_worker'));

ALTER TABLE session
    ADD COLUMN owner_id TEXT;

ALTER TABLE session
    ADD COLUMN supervisor_id TEXT;

ALTER TABLE session
    ADD COLUMN lease_ttl_secs INTEGER;

ALTER TABLE session
    ADD COLUMN last_heartbeat_at_epoch_s INTEGER;

ALTER TABLE session
    ADD COLUMN revision INTEGER NOT NULL DEFAULT 0;

UPDATE session
SET owner_kind = 'interactive'
WHERE owner_kind IS NULL
  AND session_id IS NOT NULL;

UPDATE session
SET owner_id = 'interactive'
WHERE owner_id IS NULL
  AND session_id IS NOT NULL;

UPDATE session
SET revision = 1
WHERE session_id IS NOT NULL
  AND revision = 0;
"#,
    )?;
    Ok(())
}

fn migrate_v6_to_v7(conn: &Connection) -> Result<()> {
    if !table_has_column(conn, "handoff", "revision")? {
        conn.execute_batch(
            r#"
ALTER TABLE handoff
    ADD COLUMN revision INTEGER NOT NULL DEFAULT 0;

UPDATE handoff
SET revision = 1
WHERE revision = 0
  AND (
    title != ''
    OR immediate_actions != '[]'
    OR completed_state != '[]'
    OR operational_guardrails != '[]'
    OR key_files != '[]'
    OR definition_of_done != '[]'
  );
"#,
        )?;
    }

    if !table_has_column(conn, "execution_gates", "revision")? {
        conn.execute_batch(
            r#"
ALTER TABLE execution_gates
    ADD COLUMN revision INTEGER NOT NULL DEFAULT 0;

UPDATE execution_gates
SET schema_version = CASE
    WHEN schema_version < 2 THEN 2
    ELSE schema_version
END,
    revision = CASE
        WHEN revision = 0 AND gates != '[]' THEN 1
        ELSE revision
    END;
"#,
        )?;
    }

    Ok(())
}

fn migrate_v7_to_v8(conn: &Connection) -> Result<()> {
    conn.execute_batch(
        r#"
CREATE TABLE IF NOT EXISTS session_activity (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    session_id TEXT NOT NULL,
    actor_id TEXT NOT NULL,
    current_activity TEXT NOT NULL,
    updated_at_epoch_s INTEGER NOT NULL,
    session_revision INTEGER NOT NULL
);
"#,
    )?;
    Ok(())
}

fn migrate_v8_to_v9(conn: &Connection) -> Result<()> {
    conn.execute_batch(
        r#"
CREATE TABLE IF NOT EXISTS memory_op_queue (
    id TEXT PRIMARY KEY,
    command TEXT NOT NULL,
    request_fingerprint TEXT NOT NULL,
    plan_json TEXT NOT NULL,
    staged_at_epoch_s INTEGER NOT NULL,
    updated_at_epoch_s INTEGER NOT NULL,
    actor_id TEXT,
    session_id TEXT,
    reconciled INTEGER NOT NULL DEFAULT 0,
    outcome TEXT,
    authored_entry_ids TEXT NOT NULL DEFAULT '[]',
    authored_target_path TEXT,
    authored_source_path TEXT,
    snapshot_json TEXT
);
"#,
    )?;
    Ok(())
}

fn migrate_v9_to_v10(conn: &Connection) -> Result<()> {
    if table_has_column(conn, "telemetry_cost", "focus_key")? {
        conn.execute_batch("ALTER TABLE telemetry_cost RENAME COLUMN focus_key TO next_step_key;")?;
    }
    if table_has_column(conn, "telemetry_cost", "focus_title")? {
        conn.execute_batch(
            "ALTER TABLE telemetry_cost RENAME COLUMN focus_title TO next_step_title;",
        )?;
    }
    conn.execute_batch(
        r#"
DROP INDEX IF EXISTS telemetry_cost_focus_key_idx;
CREATE INDEX IF NOT EXISTS telemetry_cost_next_step_key_idx
    ON telemetry_cost (next_step_key);
"#,
    )?;
    Ok(())
}

fn migrate_v10_to_v11(conn: &Connection) -> Result<()> {
    if !table_has_column(conn, "projection_metadata", "session_id")? {
        conn.execute_batch("ALTER TABLE projection_metadata ADD COLUMN session_id TEXT;")?;
    }
    Ok(())
}

fn migrate_v11_to_v12(conn: &Connection) -> Result<()> {
    conn.execute_batch(
        r#"
CREATE TABLE IF NOT EXISTS memory_evidence (
    id TEXT PRIMARY KEY,
    scope TEXT NOT NULL CHECK (scope IN ('workspace', 'work_stream', 'project', 'profile', 'pod', 'project_truth')),
    entry_type TEXT NOT NULL CHECK (entry_type IN ('rule', 'constraint', 'heuristic', 'observation', 'attempt')),
    source_kind TEXT NOT NULL CHECK (source_kind IN ('transcript', 'session', 'event_stream', 'hook_output', 'log', 'document')),
    summary TEXT NOT NULL,
    summary_digest TEXT NOT NULL,
    observed_at_epoch_s INTEGER NOT NULL,
    actor_id TEXT,
    session_id TEXT,
    source_ref TEXT,
    host TEXT,
    host_hook TEXT,
    host_session_id TEXT,
    host_run_id TEXT,
    host_task_id TEXT,
    provider_name TEXT,
    provider_ref TEXT,
    extracted INTEGER NOT NULL DEFAULT 0,
    extracted_candidate_id TEXT,
    extracted_at_epoch_s INTEGER
);

CREATE INDEX IF NOT EXISTS memory_evidence_extracted_idx
    ON memory_evidence (extracted, observed_at_epoch_s);
"#,
    )?;
    Ok(())
}

fn migrate_v12_to_v13(conn: &Connection) -> Result<()> {
    conn.execute_batch(
        r#"
CREATE TABLE IF NOT EXISTS host_loop_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    session_id TEXT,
    host TEXT NOT NULL,
    hook TEXT NOT NULL,
    status TEXT NOT NULL,
    session_boundary_action TEXT,
    source_fingerprint TEXT,
    normalized_payload_hash TEXT,
    payload_chars INTEGER,
    payload_estimated_tokens INTEGER,
    host_total_context_chars INTEGER,
    overhead_ratio REAL,
    session_started_at_epoch_s INTEGER,
    session_last_started_at_epoch_s INTEGER,
    session_start_count INTEGER,
    section_metrics_json TEXT
);

CREATE INDEX IF NOT EXISTS host_loop_events_observed_idx
    ON host_loop_events (observed_at_epoch_s DESC);

CREATE INDEX IF NOT EXISTS host_loop_events_host_hook_idx
    ON host_loop_events (host, hook, observed_at_epoch_s DESC);
"#,
    )?;
    Ok(())
}

fn migrate_v13_to_v14(conn: &Connection) -> Result<()> {
    conn.execute_batch(
        r#"
CREATE TABLE IF NOT EXISTS projection_cache_entries (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    target TEXT NOT NULL CHECK (target IN ('default', 'planning', 'session')),
    format TEXT NOT NULL CHECK (format IN ('narrative', 'symbolic', 'bundle')),
    source_fingerprint TEXT NOT NULL,
    tool_surface_fingerprint TEXT NOT NULL DEFAULT '',
    payload_json TEXT NOT NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS projection_cache_entries_key_idx
    ON projection_cache_entries (target, format, source_fingerprint, tool_surface_fingerprint);

CREATE INDEX IF NOT EXISTS projection_cache_entries_observed_idx
    ON projection_cache_entries (observed_at_epoch_s DESC);

CREATE TABLE IF NOT EXISTS projection_cache_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    session_id TEXT,
    target TEXT NOT NULL CHECK (target IN ('default', 'planning', 'session')),
    format TEXT NOT NULL CHECK (format IN ('narrative', 'symbolic', 'bundle')),
    source_fingerprint TEXT NOT NULL,
    tool_surface_fingerprint TEXT NOT NULL DEFAULT '',
    cache_status TEXT NOT NULL CHECK (cache_status IN ('hit', 'miss'))
);

CREATE INDEX IF NOT EXISTS projection_cache_events_target_format_idx
    ON projection_cache_events (target, format, observed_at_epoch_s DESC);

CREATE INDEX IF NOT EXISTS projection_cache_events_session_idx
    ON projection_cache_events (session_id, observed_at_epoch_s DESC);

CREATE TABLE IF NOT EXISTS work_stream_decay (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    session_id TEXT NOT NULL,
    consecutive_no_progress INTEGER NOT NULL DEFAULT 0,
    last_outcome TEXT NOT NULL CHECK (last_outcome IN ('progress', 'no_progress', 'neutral')),
    updated_at_epoch_s INTEGER NOT NULL,
    last_progress_at_epoch_s INTEGER
);
"#,
    )?;
    Ok(())
}

fn migrate_v14_to_v15(conn: &Connection) -> Result<()> {
    if !table_exists(conn, TELEMETRY_COST_TABLE)? {
        return Ok(());
    }

    if !has_legacy_telemetry_identity(conn)? {
        return Ok(());
    }

    conn.execute_batch(
        r#"
DROP INDEX IF EXISTS telemetry_cost_next_step_key_idx;
ALTER TABLE telemetry_cost RENAME TO telemetry_cost_v14;

CREATE TABLE telemetry_cost (
    session_id TEXT PRIMARY KEY,
    recorded_at_epoch_s INTEGER NOT NULL,
    next_step_key TEXT NOT NULL DEFAULT '',
    next_step_title TEXT,
    model TEXT,
    session_cost_usd REAL NOT NULL,
    input_tokens INTEGER NOT NULL DEFAULT 0,
    output_tokens INTEGER NOT NULL DEFAULT 0,
    cache_creation_input_tokens INTEGER NOT NULL DEFAULT 0,
    cache_read_input_tokens INTEGER NOT NULL DEFAULT 0,
    blended_total_tokens INTEGER
);

INSERT INTO telemetry_cost
    (session_id, recorded_at_epoch_s, next_step_key, next_step_title,
     model, session_cost_usd, input_tokens, output_tokens,
     cache_creation_input_tokens, cache_read_input_tokens, blended_total_tokens)
SELECT
    session_id, recorded_at_epoch_s, next_step_key, next_step_title,
    model, session_cost_usd, input_tokens, output_tokens,
    cache_creation_input_tokens, cache_read_input_tokens, blended_total_tokens
FROM telemetry_cost_v14;

DROP TABLE telemetry_cost_v14;

CREATE INDEX IF NOT EXISTS telemetry_cost_next_step_key_idx
    ON telemetry_cost (next_step_key);
"#,
    )?;
    Ok(())
}

// RFC 0006 M4(c): drop `'pod'` from the `memory_evidence.scope` CHECK enum.
// The bump is fail-closed: refuses advancement when either residual
// `scope='pod'` rows still exist or `~/.ccd/pods/` contains un-migrated pods.
// The prior schema stays intact on refusal — all gates run before DDL, and
// the DDL itself runs inside an explicit transaction so an interruption
// leaves either the pre-migration or post-migration state, never a half-
// rebuilt one. A leftover `memory_evidence_v15` from an earlier interrupted
// attempt is surfaced as an error rather than being silently accepted.
fn migrate_v15_to_v16_with_pods_root(conn: &Connection, pods_root: Option<&Path>) -> Result<()> {
    let has_current = table_exists(conn, "memory_evidence")?;
    let has_leftover = table_exists(conn, "memory_evidence_v15")?;

    if has_leftover {
        // An earlier v15→v16 attempt died after the rename but before the
        // rewrite completed. The DB is in a partial state; we cannot
        // silently bump user_version without resolving it.
        bail!(
            "state.db schema bump to v16 refused: leftover `memory_evidence_v15` table detected \
             from an interrupted earlier migration. Restore the state.db from backup or drop \
             the leftover table manually before retrying; the prior schema is untouched."
        );
    }

    if !has_current {
        // Fresh/partial DB with no memory_evidence table. The caller-side
        // repair path (`repair_zero_version_schema`) is responsible for
        // creating the v16 shape via SCHEMA_CURRENT; nothing to rebuild here.
        // Gate (b) still fires independently on that path so the environment
        // invariant is enforced even for this no-op.
        return Ok(());
    }

    // Gate (a): reject residual pod-scoped evidence rows.
    check_pod_layer_collapse_gate_a(conn)?;

    // Gate (b): reject un-migrated pod directories under `~/.ccd/pods/`.
    if let Some(pods_root) = pods_root {
        check_pod_layer_collapse_gate_b(pods_root)?;
    }

    // CHECK constraint cannot be altered in place; rebuild the table with the
    // restricted enum, copy the surviving rows, and re-create the index.
    // Wrap the rewrite in an explicit transaction so a failure mid-way (disk
    // full, SIGKILL, SQLite error) leaves the pre-migration schema on disk
    // rather than a partially-renamed one.
    conn.execute_batch("BEGIN")?;
    let ddl = conn.execute_batch(
        r#"
DROP INDEX IF EXISTS memory_evidence_extracted_idx;
ALTER TABLE memory_evidence RENAME TO memory_evidence_v15;

CREATE TABLE memory_evidence (
    id TEXT PRIMARY KEY,
    scope TEXT NOT NULL CHECK (scope IN ('workspace', 'work_stream', 'project', 'profile', 'project_truth')),
    entry_type TEXT NOT NULL CHECK (entry_type IN ('rule', 'constraint', 'heuristic', 'observation', 'attempt')),
    source_kind TEXT NOT NULL CHECK (source_kind IN ('transcript', 'session', 'event_stream', 'hook_output', 'log', 'document')),
    summary TEXT NOT NULL,
    summary_digest TEXT NOT NULL,
    observed_at_epoch_s INTEGER NOT NULL,
    actor_id TEXT,
    session_id TEXT,
    source_ref TEXT,
    host TEXT,
    host_hook TEXT,
    host_session_id TEXT,
    host_run_id TEXT,
    host_task_id TEXT,
    provider_name TEXT,
    provider_ref TEXT,
    extracted INTEGER NOT NULL DEFAULT 0,
    extracted_candidate_id TEXT,
    extracted_at_epoch_s INTEGER
);

INSERT INTO memory_evidence
    (id, scope, entry_type, source_kind, summary, summary_digest,
     observed_at_epoch_s, actor_id, session_id, source_ref, host, host_hook,
     host_session_id, host_run_id, host_task_id, provider_name, provider_ref,
     extracted, extracted_candidate_id, extracted_at_epoch_s)
SELECT
    id, scope, entry_type, source_kind, summary, summary_digest,
    observed_at_epoch_s, actor_id, session_id, source_ref, host, host_hook,
    host_session_id, host_run_id, host_task_id, provider_name, provider_ref,
    extracted, extracted_candidate_id, extracted_at_epoch_s
FROM memory_evidence_v15;

DROP TABLE memory_evidence_v15;

CREATE INDEX IF NOT EXISTS memory_evidence_extracted_idx
    ON memory_evidence (extracted, observed_at_epoch_s);
"#,
    );
    match ddl {
        Ok(()) => {
            conn.execute_batch("COMMIT")?;
            Ok(())
        }
        Err(error) => {
            let _ = conn.execute_batch("ROLLBACK");
            Err(error.into())
        }
    }
}

fn check_pod_layer_collapse_gate_a(conn: &Connection) -> Result<()> {
    let pod_row_count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM memory_evidence WHERE scope = 'pod'",
        [],
        |row| row.get(0),
    )?;
    if pod_row_count > 0 {
        bail!(
            "state.db schema bump to v16 refused: {pod_row_count} memory_evidence row(s) \
             still have scope='pod'. Run `ccd migrate from-pod-layout` and retire residual \
             pod-scoped evidence before retrying; the prior schema is untouched."
        );
    }
    Ok(())
}

fn check_pod_layer_collapse_gate_b(pods_root: &Path) -> Result<()> {
    let offenders = find_unmigrated_pods(pods_root)?;
    if offenders.is_empty() {
        return Ok(());
    }
    // Group offenders by kind so the error tells the operator what's actually
    // wrong for each pod (missing marker vs. stale marker over live sources).
    let mut missing_marker: Vec<&str> = Vec::new();
    let mut stale_marker: Vec<String> = Vec::new();
    for offender in &offenders {
        match offender {
            PodOffender::MissingMarker { name } => missing_marker.push(name),
            PodOffender::StaleMarkerOverSources { name, sources } => {
                stale_marker.push(format!("{name} (pending: {})", sources.join(", ")));
            }
        }
    }
    let mut detail_parts: Vec<String> = Vec::new();
    if !missing_marker.is_empty() {
        let (noun, verb) = if missing_marker.len() == 1 {
            ("directory", "lacks")
        } else {
            ("directories", "lack")
        };
        detail_parts.push(format!(
            "{} pod {noun} {verb} MIGRATED.md ({})",
            missing_marker.len(),
            missing_marker.join(", ")
        ));
    }
    if !stale_marker.is_empty() {
        let (noun, verb) = if stale_marker.len() == 1 {
            ("directory", "carries")
        } else {
            ("directories", "carry")
        };
        detail_parts.push(format!(
            "{} pod {noun} {verb} MIGRATED.md but still hold pod-scoped sources [{}]",
            stale_marker.len(),
            stale_marker.join("; ")
        ));
    }
    bail!(
        "state.db schema bump to v16 refused under {pods_root}: {detail}. Run \
         `ccd migrate from-pod-layout` before retrying; the prior schema is untouched.",
        pods_root = pods_root.display(),
        detail = detail_parts.join("; "),
    );
}

// Markers that identify a directory under `~/.ccd/pods/` as a real pod the
// collapse actually needs to handle. A subdir that carries none of these is
// treated as foreign (backup, scratch, unrelated tool) and does not block the
// v15→v16 bump. This mirrors the real-pod detection in
// `ccd migrate from-pod-layout` (see `src/commands/migrate.rs::scan_pending_pod`
// and `PodManifestFile`): only pods with operator-visible artifacts are
// material to the collapse.
const POD_MARKER_NAMES: &[&str] = &[
    "pod.toml",
    "machine.toml",
    "memory.md",
    "policy.md",
    "presence",
    "repos",
];

// Pod-scoped source files that `ccd migrate from-pod-layout` still needs to
// relocate. If a pod directory carries MIGRATED.md AND any of these, the
// marker is stale — the earlier migration attempt did not complete and the
// state is ambiguous. Keep in sync with
// `src/commands/migrate.rs::find_pending_source_files`.
const PENDING_SOURCE_NAMES: &[&str] = &["machine.toml"];
const PENDING_PRESENCE_DIR: &str = "presence";

fn is_pod_dir(path: &Path) -> bool {
    POD_MARKER_NAMES
        .iter()
        .any(|marker| path.join(marker).exists())
}

enum PodOffender {
    /// Pod directory exists but `MIGRATED.md` is missing.
    MissingMarker { name: String },
    /// `MIGRATED.md` is present but pod-scoped sources still sit alongside
    /// it, so the marker is not trustworthy.
    StaleMarkerOverSources { name: String, sources: Vec<String> },
}

fn find_unmigrated_pods(pods_root: &Path) -> Result<Vec<PodOffender>> {
    let iter = match std::fs::read_dir(pods_root) {
        Ok(iter) => iter,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => bail!("failed to read {}: {error}", pods_root.display()),
    };
    let mut offenders = Vec::new();
    for entry in iter {
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            continue;
        }
        let path = entry.path();
        if !is_pod_dir(&path) {
            // Foreign directory under pods_root (backup, scratch, unrelated
            // tool); the migration tool does not touch it, so the gate must
            // not block startup on its behalf.
            continue;
        }
        let name = entry
            .file_name()
            .to_str()
            .map(String::from)
            .unwrap_or_else(|| path.display().to_string());
        let marker = path.join("MIGRATED.md");
        if !marker.is_file() {
            offenders.push(PodOffender::MissingMarker { name });
            continue;
        }
        let sources = pending_pod_sources(&path)?;
        if !sources.is_empty() {
            offenders.push(PodOffender::StaleMarkerOverSources { name, sources });
        }
    }
    offenders.sort_by(|a, b| offender_name(a).cmp(offender_name(b)));
    Ok(offenders)
}

fn offender_name(offender: &PodOffender) -> &str {
    match offender {
        PodOffender::MissingMarker { name } => name,
        PodOffender::StaleMarkerOverSources { name, .. } => name,
    }
}

fn pending_pod_sources(pod_dir: &Path) -> Result<Vec<String>> {
    let mut pending = Vec::new();
    for leaf in PENDING_SOURCE_NAMES {
        let candidate = pod_dir.join(leaf);
        if candidate.is_file() {
            pending.push((*leaf).to_string());
        }
    }
    let presence_root = pod_dir.join(PENDING_PRESENCE_DIR);
    if presence_root.is_dir() {
        let entries = match std::fs::read_dir(&presence_root) {
            Ok(entries) => entries,
            Err(error) => bail!("failed to read {}: {error}", presence_root.display()),
        };
        for entry in entries {
            let entry = entry?;
            if !entry.file_type()?.is_file() {
                continue;
            }
            let file_name = entry.file_name();
            let name = match file_name.to_str() {
                Some(name) => name,
                None => continue,
            };
            if name.ends_with(".json") {
                pending.push(format!("{PENDING_PRESENCE_DIR}/{name}"));
            }
        }
    }
    pending.sort();
    Ok(pending)
}

fn memory_evidence_check_allows_pod(conn: &Connection) -> Result<bool> {
    let sql: Option<String> = conn
        .query_row(
            "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'memory_evidence'",
            [],
            |row| row.get(0),
        )
        .ok();
    Ok(sql.is_some_and(|s| s.contains("'pod'")))
}

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

    #[test]
    fn table_has_column_rejects_empty_table_name() {
        let conn = Connection::open_in_memory().unwrap();
        let err = table_has_column(&conn, "", "x").unwrap_err();
        assert!(
            err.to_string().contains("invalid SQL identifier"),
            "got: {err}"
        );
    }

    #[test]
    fn table_has_column_rejects_digit_leading_table_name() {
        let conn = Connection::open_in_memory().unwrap();
        let err = table_has_column(&conn, "123foo", "x").unwrap_err();
        assert!(
            err.to_string().contains("invalid SQL identifier"),
            "got: {err}"
        );
    }

    #[test]
    fn table_has_column_rejects_table_name_with_semicolon() {
        let conn = Connection::open_in_memory().unwrap();
        let err = table_has_column(&conn, "foo; DROP TABLE bar", "x").unwrap_err();
        assert!(
            err.to_string().contains("invalid SQL identifier"),
            "got: {err}"
        );
    }

    #[test]
    fn table_has_column_rejects_table_name_with_space() {
        let conn = Connection::open_in_memory().unwrap();
        let err = table_has_column(&conn, "foo bar", "x").unwrap_err();
        assert!(
            err.to_string().contains("invalid SQL identifier"),
            "got: {err}"
        );
    }

    #[test]
    fn table_has_column_rejects_table_name_with_quote() {
        let conn = Connection::open_in_memory().unwrap();
        let err = table_has_column(&conn, "foo\"bar", "x").unwrap_err();
        assert!(
            err.to_string().contains("invalid SQL identifier"),
            "got: {err}"
        );
    }

    #[test]
    fn table_has_column_accepts_valid_identifier() {
        let conn = Connection::open_in_memory().unwrap();
        initialize(&conn, None).unwrap();
        // `session` exists with a `mode` column in the current schema.
        assert!(table_has_column(&conn, "session", "mode").unwrap());
        // A valid identifier for a nonexistent column returns Ok(false).
        assert!(!table_has_column(&conn, "session", "no_such_column").unwrap());
    }

    #[test]
    fn initialize_creates_all_tables() {
        let conn = Connection::open_in_memory().unwrap();
        initialize(&conn, None).unwrap();
        let version: u32 = conn
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version, CURRENT_VERSION);

        for table in [
            "handoff",
            "session",
            "session_activity",
            "escalation",
            "recovery",
            "projection_metadata",
            "execution_gates",
            "telemetry_cost",
            "host_loop_events",
            "projection_cache_entries",
            "projection_cache_events",
            "work_stream_decay",
            "memory_op_queue",
            "memory_evidence",
        ] {
            let count: i64 = conn
                .query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| {
                    row.get(0)
                })
                .unwrap();
            assert_eq!(count, 0, "table {table} should exist and be empty");
        }
    }

    #[test]
    fn migrate_is_idempotent() {
        let conn = Connection::open_in_memory().unwrap();
        initialize(&conn, None).unwrap();
        migrate(&conn, None).unwrap();
        let version: u32 = conn
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version, CURRENT_VERSION);
    }

    #[test]
    fn migrate_rejects_future_version() {
        let conn = Connection::open_in_memory().unwrap();
        initialize(&conn, None).unwrap();
        conn.pragma_update(None, "user_version", CURRENT_VERSION + 1)
            .unwrap();
        let result = migrate(&conn, None);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("newer than supported"));
    }

    #[test]
    fn migrate_recovers_version_zero_db() {
        // Simulate a truncated/touched DB with user_version=0 and no tables
        let conn = Connection::open_in_memory().unwrap();
        // Don't call initialize — just migrate from version 0
        migrate(&conn, None).unwrap();

        let version: u32 = conn
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version, CURRENT_VERSION);

        // All tables should exist
        for table in [
            "handoff",
            "session",
            "session_activity",
            "escalation",
            "recovery",
            "projection_metadata",
            "execution_gates",
            "telemetry_cost",
            "host_loop_events",
            "memory_op_queue",
            "memory_evidence",
        ] {
            let count: i64 = conn
                .query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| {
                    row.get(0)
                })
                .unwrap();
            assert_eq!(count, 0, "table {table} should exist after v0 recovery");
        }
    }

    #[test]
    fn migrate_repairs_version_zero_partial_session_schema() {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            r#"
CREATE TABLE session (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 3,
    started_at_epoch_s INTEGER NOT NULL,
    last_started_at_epoch_s INTEGER NOT NULL,
    start_count INTEGER NOT NULL DEFAULT 1,
    session_id TEXT
);
"#,
        )
        .unwrap();
        conn.execute(
            "INSERT INTO session
                (id, schema_version, started_at_epoch_s, last_started_at_epoch_s, start_count, session_id)
             VALUES (1, 3, 10, 10, 1, 'ses_partial')",
            [],
        )
        .unwrap();

        migrate(&conn, None).unwrap();

        let columns = conn
            .prepare("PRAGMA table_info(session)")
            .unwrap()
            .query_map([], |row| row.get::<_, String>(1))
            .unwrap()
            .collect::<rusqlite::Result<Vec<_>>>()
            .unwrap();
        assert!(columns.iter().any(|column| column == "mode"));
        assert!(columns.iter().any(|column| column == "owner_kind"));
        assert!(columns.iter().any(|column| column == "revision"));

        let mode: String = conn
            .query_row("SELECT mode FROM session WHERE id = 1", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(mode, "general");

        let owner_kind: String = conn
            .query_row("SELECT owner_kind FROM session WHERE id = 1", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(owner_kind, "interactive");

        let revision: u64 = conn
            .query_row("SELECT revision FROM session WHERE id = 1", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(revision, 1);
    }

    #[test]
    fn migrate_v1_to_v2_drops_current_system_state_column() {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            r#"
CREATE TABLE handoff (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    title TEXT NOT NULL DEFAULT '',
    immediate_actions TEXT NOT NULL DEFAULT '[]',
    completed_state TEXT NOT NULL DEFAULT '[]',
    current_system_state TEXT NOT NULL DEFAULT '[]',
    operational_guardrails TEXT NOT NULL DEFAULT '[]',
    key_files TEXT NOT NULL DEFAULT '[]',
    definition_of_done TEXT NOT NULL DEFAULT '[]'
);

CREATE TABLE session (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 3,
    started_at_epoch_s INTEGER NOT NULL,
    last_started_at_epoch_s INTEGER NOT NULL,
    start_count INTEGER NOT NULL DEFAULT 1,
    session_id TEXT
);

CREATE TABLE escalation (
    id TEXT PRIMARY KEY,
    kind TEXT NOT NULL CHECK (kind IN ('blocking', 'non_blocking')),
    reason TEXT NOT NULL,
    created_at_epoch_s INTEGER NOT NULL,
    session_id TEXT
);

CREATE TABLE recovery (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    checkpoint_origin TEXT,
    checkpoint_captured_at_epoch_s INTEGER,
    checkpoint_session_started_at_epoch_s INTEGER,
    checkpoint_summary TEXT,
    checkpoint_immediate_actions TEXT,
    checkpoint_key_files TEXT,
    buffer_origin TEXT,
    buffer_captured_at_epoch_s INTEGER,
    buffer_session_started_at_epoch_s INTEGER,
    buffer_summary_lines TEXT
);

CREATE TABLE projection_metadata (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    source_fingerprint TEXT NOT NULL,
    projection_digests TEXT,
    tool_surface_fingerprint TEXT
);
"#,
        )
        .unwrap();
        conn.pragma_update(None, "user_version", 1).unwrap();
        conn.execute(
            "INSERT INTO handoff
                (id, schema_version, title, immediate_actions, completed_state,
                 current_system_state, operational_guardrails, key_files, definition_of_done)
             VALUES (1, 1, 'Test', '[]', '[]', '[\"stale\"]', '[]', '[]', '[]')",
            [],
        )
        .unwrap();

        migrate(&conn, None).unwrap();

        let version: u32 = conn
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version, CURRENT_VERSION);

        let columns = conn
            .prepare("PRAGMA table_info(handoff)")
            .unwrap()
            .query_map([], |row| row.get::<_, String>(1))
            .unwrap()
            .collect::<rusqlite::Result<Vec<_>>>()
            .unwrap();
        assert!(!columns
            .iter()
            .any(|column| column == "current_system_state"));
    }

    #[test]
    fn migrate_v1_to_v2_recovers_from_leftover_temp_table() {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            r#"
CREATE TABLE handoff (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    title TEXT NOT NULL DEFAULT '',
    immediate_actions TEXT NOT NULL DEFAULT '[]',
    completed_state TEXT NOT NULL DEFAULT '[]',
    current_system_state TEXT NOT NULL DEFAULT '[]',
    operational_guardrails TEXT NOT NULL DEFAULT '[]',
    key_files TEXT NOT NULL DEFAULT '[]',
    definition_of_done TEXT NOT NULL DEFAULT '[]'
);

CREATE TABLE handoff_v2 (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    title TEXT NOT NULL DEFAULT '',
    immediate_actions TEXT NOT NULL DEFAULT '[]',
    completed_state TEXT NOT NULL DEFAULT '[]',
    operational_guardrails TEXT NOT NULL DEFAULT '[]',
    key_files TEXT NOT NULL DEFAULT '[]',
    definition_of_done TEXT NOT NULL DEFAULT '[]'
);

CREATE TABLE session (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 3,
    started_at_epoch_s INTEGER NOT NULL,
    last_started_at_epoch_s INTEGER NOT NULL,
    start_count INTEGER NOT NULL DEFAULT 1,
    session_id TEXT
);

CREATE TABLE escalation (
    id TEXT PRIMARY KEY,
    kind TEXT NOT NULL CHECK (kind IN ('blocking', 'non_blocking')),
    reason TEXT NOT NULL,
    created_at_epoch_s INTEGER NOT NULL,
    session_id TEXT
);

CREATE TABLE recovery (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    checkpoint_origin TEXT,
    checkpoint_captured_at_epoch_s INTEGER,
    checkpoint_session_started_at_epoch_s INTEGER,
    checkpoint_summary TEXT,
    checkpoint_immediate_actions TEXT,
    checkpoint_key_files TEXT,
    buffer_origin TEXT,
    buffer_captured_at_epoch_s INTEGER,
    buffer_session_started_at_epoch_s INTEGER,
    buffer_summary_lines TEXT
);

CREATE TABLE projection_metadata (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    source_fingerprint TEXT NOT NULL,
    projection_digests TEXT,
    tool_surface_fingerprint TEXT
);
"#,
        )
        .unwrap();
        conn.pragma_update(None, "user_version", 1).unwrap();
        conn.execute(
            "INSERT INTO handoff
                (id, schema_version, title, immediate_actions, completed_state,
                 current_system_state, operational_guardrails, key_files, definition_of_done)
             VALUES (1, 1, 'Retry-safe', '[]', '[]', '[\"stale\"]', '[]', '[]', '[]')",
            [],
        )
        .unwrap();

        migrate(&conn, None).unwrap();

        let title: String = conn
            .query_row("SELECT title FROM handoff WHERE id = 1", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(title, "Retry-safe");
    }

    #[test]
    fn migrate_v2_to_v3_adds_execution_gates_table() {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            r#"
CREATE TABLE handoff (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    title TEXT NOT NULL DEFAULT '',
    immediate_actions TEXT NOT NULL DEFAULT '[]',
    completed_state TEXT NOT NULL DEFAULT '[]',
    operational_guardrails TEXT NOT NULL DEFAULT '[]',
    key_files TEXT NOT NULL DEFAULT '[]',
    definition_of_done TEXT NOT NULL DEFAULT '[]'
);

CREATE TABLE session (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 3,
    started_at_epoch_s INTEGER NOT NULL,
    last_started_at_epoch_s INTEGER NOT NULL,
    start_count INTEGER NOT NULL DEFAULT 1,
    session_id TEXT
);

CREATE TABLE escalation (
    id TEXT PRIMARY KEY,
    kind TEXT NOT NULL CHECK (kind IN ('blocking', 'non_blocking')),
    reason TEXT NOT NULL,
    created_at_epoch_s INTEGER NOT NULL,
    session_id TEXT
);

CREATE TABLE recovery (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    checkpoint_origin TEXT,
    checkpoint_captured_at_epoch_s INTEGER,
    checkpoint_session_started_at_epoch_s INTEGER,
    checkpoint_summary TEXT,
    checkpoint_immediate_actions TEXT,
    checkpoint_key_files TEXT,
    buffer_origin TEXT,
    buffer_captured_at_epoch_s INTEGER,
    buffer_session_started_at_epoch_s INTEGER,
    buffer_summary_lines TEXT
);

CREATE TABLE projection_metadata (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    source_fingerprint TEXT NOT NULL,
    projection_digests TEXT,
    tool_surface_fingerprint TEXT
);
"#,
        )
        .unwrap();
        conn.pragma_update(None, "user_version", 2).unwrap();

        migrate(&conn, None).unwrap();

        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM execution_gates", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);
    }

    #[test]
    fn migrate_v3_to_v4_adds_session_mode_column() {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            r#"
CREATE TABLE handoff (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    title TEXT NOT NULL DEFAULT '',
    immediate_actions TEXT NOT NULL DEFAULT '[]',
    completed_state TEXT NOT NULL DEFAULT '[]',
    operational_guardrails TEXT NOT NULL DEFAULT '[]',
    key_files TEXT NOT NULL DEFAULT '[]',
    definition_of_done TEXT NOT NULL DEFAULT '[]'
);

CREATE TABLE session (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 3,
    started_at_epoch_s INTEGER NOT NULL,
    last_started_at_epoch_s INTEGER NOT NULL,
    start_count INTEGER NOT NULL DEFAULT 1,
    session_id TEXT
);

CREATE TABLE escalation (
    id TEXT PRIMARY KEY,
    kind TEXT NOT NULL CHECK (kind IN ('blocking', 'non_blocking')),
    reason TEXT NOT NULL,
    created_at_epoch_s INTEGER NOT NULL,
    session_id TEXT
);

CREATE TABLE recovery (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    checkpoint_origin TEXT,
    checkpoint_captured_at_epoch_s INTEGER,
    checkpoint_session_started_at_epoch_s INTEGER,
    checkpoint_summary TEXT,
    checkpoint_immediate_actions TEXT,
    checkpoint_key_files TEXT,
    buffer_origin TEXT,
    buffer_captured_at_epoch_s INTEGER,
    buffer_session_started_at_epoch_s INTEGER,
    buffer_summary_lines TEXT
);

CREATE TABLE projection_metadata (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    source_fingerprint TEXT NOT NULL,
    projection_digests TEXT,
    tool_surface_fingerprint TEXT
);

CREATE TABLE execution_gates (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    seeded_from TEXT,
    gates TEXT NOT NULL DEFAULT '[]'
);
"#,
        )
        .unwrap();
        conn.pragma_update(None, "user_version", 3).unwrap();
        conn.execute(
            "INSERT INTO session
                (id, schema_version, started_at_epoch_s, last_started_at_epoch_s, start_count, session_id)
             VALUES (1, 3, 1000, 1000, 1, 'ses_V3')",
            [],
        )
        .unwrap();

        migrate(&conn, None).unwrap();

        let mode: String = conn
            .query_row("SELECT mode FROM session WHERE id = 1", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(mode, "general");

        let owner_kind: String = conn
            .query_row("SELECT owner_kind FROM session WHERE id = 1", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(owner_kind, "interactive");

        let revision: u64 = conn
            .query_row("SELECT revision FROM session WHERE id = 1", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(revision, 1);
    }

    #[test]
    fn migrate_v6_to_v8_adds_session_activity_table_without_disturbing_surface_revisions() {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            r#"
CREATE TABLE handoff (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    title TEXT NOT NULL DEFAULT '',
    immediate_actions TEXT NOT NULL DEFAULT '[]',
    completed_state TEXT NOT NULL DEFAULT '[]',
    operational_guardrails TEXT NOT NULL DEFAULT '[]',
    key_files TEXT NOT NULL DEFAULT '[]',
    definition_of_done TEXT NOT NULL DEFAULT '[]'
);

CREATE TABLE session (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 4,
    started_at_epoch_s INTEGER NOT NULL,
    last_started_at_epoch_s INTEGER NOT NULL,
    start_count INTEGER NOT NULL DEFAULT 1,
    session_id TEXT,
    mode TEXT NOT NULL DEFAULT 'general' CHECK (mode IN ('general', 'research', 'implement')),
    owner_kind TEXT CHECK (owner_kind IN ('interactive', 'runtime_supervisor', 'runtime_worker')),
    owner_id TEXT,
    supervisor_id TEXT,
    lease_ttl_secs INTEGER,
    last_heartbeat_at_epoch_s INTEGER,
    revision INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE escalation (
    id TEXT PRIMARY KEY,
    kind TEXT NOT NULL CHECK (kind IN ('blocking', 'non_blocking')),
    reason TEXT NOT NULL,
    created_at_epoch_s INTEGER NOT NULL,
    session_id TEXT
);

CREATE TABLE recovery (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    checkpoint_origin TEXT,
    checkpoint_captured_at_epoch_s INTEGER,
    checkpoint_session_started_at_epoch_s INTEGER,
    checkpoint_summary TEXT,
    checkpoint_immediate_actions TEXT,
    checkpoint_key_files TEXT,
    buffer_origin TEXT,
    buffer_captured_at_epoch_s INTEGER,
    buffer_session_started_at_epoch_s INTEGER,
    buffer_summary_lines TEXT
);

CREATE TABLE projection_metadata (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    source_fingerprint TEXT NOT NULL,
    projection_digests TEXT,
    tool_surface_fingerprint TEXT
);

CREATE TABLE execution_gates (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    seeded_from TEXT,
    gates TEXT NOT NULL DEFAULT '[]'
);

CREATE TABLE telemetry_cost (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    backlog_item_ref TEXT NOT NULL,
    focus_key TEXT NOT NULL DEFAULT '',
    observed_at_epoch_s INTEGER NOT NULL,
    host TEXT,
    model TEXT,
    cost_usd REAL,
    total_tokens INTEGER,
    input_tokens INTEGER,
    output_tokens INTEGER,
    context_used_pct INTEGER,
    context_window_tokens INTEGER,
    compacted INTEGER
);
"#,
        )
        .unwrap();
        conn.pragma_update(None, "user_version", 6).unwrap();
        conn.execute(
            "INSERT INTO handoff
                (id, schema_version, title, immediate_actions, completed_state, operational_guardrails, key_files, definition_of_done)
             VALUES (1, 1, 'Seeded', '[\"one\"]', '[]', '[]', '[]', '[\"done\"]')",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO execution_gates (id, schema_version, seeded_from, gates)
             VALUES (1, 1, 'handoff:immediate_actions', '[{\"text\":\"gate\",\"status\":\"open\"}]')",
            [],
        )
        .unwrap();

        migrate(&conn, None).unwrap();

        let handoff_revision: u64 = conn
            .query_row("SELECT revision FROM handoff WHERE id = 1", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(handoff_revision, 1);

        let gate_schema_version: u32 = conn
            .query_row(
                "SELECT schema_version FROM execution_gates WHERE id = 1",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(gate_schema_version, 2);

        let gate_revision: u64 = conn
            .query_row(
                "SELECT revision FROM execution_gates WHERE id = 1",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(gate_revision, 1);

        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM session_activity", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(count, 0);
    }

    #[test]
    fn migrate_v9_to_v10_renames_focus_columns() {
        let conn = Connection::open_in_memory().unwrap();
        // Set up a v9 database with the old column names
        conn.execute_batch(
            r#"
CREATE TABLE telemetry_cost (
    session_id TEXT PRIMARY KEY,
    recorded_at_epoch_s INTEGER NOT NULL,
    focus_key TEXT NOT NULL DEFAULT '',
    focus_title TEXT,
    ccd_id INTEGER NOT NULL DEFAULT 0,
    github_issue_number INTEGER NOT NULL DEFAULT 0,
    backlog_provider TEXT,
    backlog_kind TEXT,
    backlog_id TEXT,
    backlog_url TEXT,
    model TEXT,
    session_cost_usd REAL NOT NULL,
    input_tokens INTEGER NOT NULL DEFAULT 0,
    output_tokens INTEGER NOT NULL DEFAULT 0,
    cache_creation_input_tokens INTEGER NOT NULL DEFAULT 0,
    cache_read_input_tokens INTEGER NOT NULL DEFAULT 0,
    blended_total_tokens INTEGER
);

CREATE INDEX telemetry_cost_focus_key_idx
    ON telemetry_cost (focus_key);

INSERT INTO telemetry_cost
    (session_id, recorded_at_epoch_s, focus_key, focus_title,
     session_cost_usd)
VALUES
    ('ses_1', 1000, 'ccd:42', 'Widget refactor', 1.50);
"#,
        )
        .unwrap();

        migrate_v9_to_v10(&conn).unwrap();

        // Old columns should be gone
        assert!(!table_has_column(&conn, "telemetry_cost", "focus_key").unwrap());
        assert!(!table_has_column(&conn, "telemetry_cost", "focus_title").unwrap());

        // New columns should exist with the same data
        assert!(table_has_column(&conn, "telemetry_cost", "next_step_key").unwrap());
        assert!(table_has_column(&conn, "telemetry_cost", "next_step_title").unwrap());

        let key: String = conn
            .query_row(
                "SELECT next_step_key FROM telemetry_cost WHERE session_id = 'ses_1'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(key, "ccd:42");

        let title: String = conn
            .query_row(
                "SELECT next_step_title FROM telemetry_cost WHERE session_id = 'ses_1'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(title, "Widget refactor");
    }

    #[test]
    fn migrate_v10_to_v11_adds_session_id_column() {
        let conn = Connection::open_in_memory().unwrap();
        // Set up a v10 database with the projection_metadata table lacking session_id
        conn.execute_batch(
            r#"
CREATE TABLE projection_metadata (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    source_fingerprint TEXT NOT NULL,
    projection_digests TEXT,
    tool_surface_fingerprint TEXT
);

INSERT INTO projection_metadata
    (observed_at_epoch_s, source_fingerprint, projection_digests, tool_surface_fingerprint)
VALUES
    (1000, 'fp_1', NULL, 'tool_abc');
"#,
        )
        .unwrap();

        migrate_v10_to_v11(&conn).unwrap();

        // session_id column should exist
        assert!(table_has_column(&conn, "projection_metadata", "session_id").unwrap());

        // Existing row should have NULL session_id
        let session_id: Option<String> = conn
            .query_row(
                "SELECT session_id FROM projection_metadata WHERE source_fingerprint = 'fp_1'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert!(session_id.is_none());

        // Should be able to insert a row with session_id
        conn.execute(
            "INSERT INTO projection_metadata
                (observed_at_epoch_s, source_fingerprint, projection_digests,
                 tool_surface_fingerprint, session_id)
             VALUES (2000, 'fp_2', NULL, NULL, 'ses_test')",
            [],
        )
        .unwrap();

        let session_id: Option<String> = conn
            .query_row(
                "SELECT session_id FROM projection_metadata WHERE source_fingerprint = 'fp_2'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(session_id.as_deref(), Some("ses_test"));

        // Idempotent — running again should not fail
        migrate_v10_to_v11(&conn).unwrap();
    }

    #[test]
    fn migrate_v11_to_v12_adds_memory_evidence_table() {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            r#"
CREATE TABLE handoff (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    title TEXT NOT NULL DEFAULT '',
    immediate_actions TEXT NOT NULL DEFAULT '[]',
    completed_state TEXT NOT NULL DEFAULT '[]',
    operational_guardrails TEXT NOT NULL DEFAULT '[]',
    key_files TEXT NOT NULL DEFAULT '[]',
    definition_of_done TEXT NOT NULL DEFAULT '[]',
    revision INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE session (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 4,
    started_at_epoch_s INTEGER NOT NULL,
    last_started_at_epoch_s INTEGER NOT NULL,
    start_count INTEGER NOT NULL DEFAULT 1,
    session_id TEXT,
    mode TEXT NOT NULL DEFAULT 'general',
    owner_kind TEXT,
    owner_id TEXT,
    supervisor_id TEXT,
    lease_ttl_secs INTEGER,
    last_heartbeat_at_epoch_s INTEGER,
    revision INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE session_activity (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    session_id TEXT NOT NULL,
    actor_id TEXT NOT NULL,
    current_activity TEXT NOT NULL,
    updated_at_epoch_s INTEGER NOT NULL,
    session_revision INTEGER NOT NULL
);

CREATE TABLE escalation (
    id TEXT PRIMARY KEY,
    kind TEXT NOT NULL CHECK (kind IN ('blocking', 'non_blocking')),
    reason TEXT NOT NULL,
    created_at_epoch_s INTEGER NOT NULL,
    session_id TEXT
);

CREATE TABLE recovery (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    checkpoint_origin TEXT,
    checkpoint_captured_at_epoch_s INTEGER,
    checkpoint_session_started_at_epoch_s INTEGER,
    checkpoint_summary TEXT,
    checkpoint_immediate_actions TEXT,
    checkpoint_key_files TEXT,
    buffer_origin TEXT,
    buffer_captured_at_epoch_s INTEGER,
    buffer_session_started_at_epoch_s INTEGER,
    buffer_summary_lines TEXT
);

CREATE TABLE projection_metadata (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    source_fingerprint TEXT NOT NULL,
    projection_digests TEXT,
    tool_surface_fingerprint TEXT,
    session_id TEXT
);

CREATE TABLE execution_gates (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 2,
    seeded_from TEXT,
    gates TEXT NOT NULL DEFAULT '[]',
    revision INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE telemetry_cost (
    session_id TEXT PRIMARY KEY,
    recorded_at_epoch_s INTEGER NOT NULL,
    next_step_key TEXT NOT NULL DEFAULT '',
    next_step_title TEXT,
    ccd_id INTEGER NOT NULL DEFAULT 0,
    github_issue_number INTEGER NOT NULL DEFAULT 0,
    backlog_provider TEXT,
    backlog_kind TEXT,
    backlog_id TEXT,
    backlog_url TEXT,
    model TEXT,
    session_cost_usd REAL NOT NULL,
    input_tokens INTEGER NOT NULL DEFAULT 0,
    output_tokens INTEGER NOT NULL DEFAULT 0,
    cache_creation_input_tokens INTEGER NOT NULL DEFAULT 0,
    cache_read_input_tokens INTEGER NOT NULL DEFAULT 0,
    blended_total_tokens INTEGER
);

CREATE INDEX telemetry_cost_next_step_key_idx
    ON telemetry_cost (next_step_key);

CREATE TABLE memory_op_queue (
    id TEXT PRIMARY KEY,
    command TEXT NOT NULL,
    request_fingerprint TEXT NOT NULL,
    plan_json TEXT NOT NULL,
    staged_at_epoch_s INTEGER NOT NULL,
    updated_at_epoch_s INTEGER NOT NULL,
    actor_id TEXT,
    session_id TEXT,
    reconciled INTEGER NOT NULL DEFAULT 0,
    outcome TEXT,
    authored_entry_ids TEXT NOT NULL DEFAULT '[]',
    authored_target_path TEXT,
    authored_source_path TEXT,
    snapshot_json TEXT
);
"#,
        )
        .unwrap();
        conn.pragma_update(None, "user_version", 11).unwrap();

        migrate(&conn, None).unwrap();

        let version: u32 = conn
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version, CURRENT_VERSION);

        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_evidence", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);
    }

    #[test]
    fn migrate_v12_to_v13_adds_host_loop_events_table() {
        let conn = Connection::open_in_memory().unwrap();
        initialize(&conn, None).unwrap();
        conn.execute_batch(
            r#"
DROP INDEX IF EXISTS host_loop_events_host_hook_idx;
DROP INDEX IF EXISTS host_loop_events_observed_idx;
DROP TABLE IF EXISTS host_loop_events;
"#,
        )
        .unwrap();
        conn.pragma_update(None, "user_version", 12).unwrap();

        migrate(&conn, None).unwrap();

        let version: u32 = conn
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version, CURRENT_VERSION);

        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM host_loop_events", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(count, 0);
    }

    #[test]
    fn migrate_v13_to_v14_adds_projection_cache_and_decay_tables() {
        let conn = Connection::open_in_memory().unwrap();
        initialize(&conn, None).unwrap();
        conn.execute_batch(
            r#"
DROP INDEX IF EXISTS projection_cache_events_session_idx;
DROP INDEX IF EXISTS projection_cache_events_target_format_idx;
DROP TABLE IF EXISTS projection_cache_events;
DROP INDEX IF EXISTS projection_cache_entries_observed_idx;
DROP INDEX IF EXISTS projection_cache_entries_key_idx;
DROP TABLE IF EXISTS projection_cache_entries;
DROP TABLE IF EXISTS work_stream_decay;
"#,
        )
        .unwrap();
        conn.pragma_update(None, "user_version", 13).unwrap();

        migrate(&conn, None).unwrap();

        let version: u32 = conn
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version, CURRENT_VERSION);

        let cache_entries: i64 = conn
            .query_row("SELECT COUNT(*) FROM projection_cache_entries", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(cache_entries, 0);

        let cache_events: i64 = conn
            .query_row("SELECT COUNT(*) FROM projection_cache_events", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(cache_events, 0);

        let decay_rows: i64 = conn
            .query_row("SELECT COUNT(*) FROM work_stream_decay", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(decay_rows, 0);
    }

    #[test]
    fn migrate_v14_to_v15_drops_legacy_telemetry_identity_columns() {
        let conn = Connection::open_in_memory().unwrap();
        initialize(&conn, None).unwrap();
        conn.execute_batch(
            r#"
DROP INDEX IF EXISTS telemetry_cost_next_step_key_idx;
DROP TABLE IF EXISTS telemetry_cost;

CREATE TABLE telemetry_cost (
    session_id TEXT PRIMARY KEY,
    recorded_at_epoch_s INTEGER NOT NULL,
    next_step_key TEXT NOT NULL DEFAULT '',
    next_step_title TEXT,
    ccd_id INTEGER NOT NULL DEFAULT 0,
    github_issue_number INTEGER NOT NULL DEFAULT 0,
    backlog_provider TEXT,
    backlog_kind TEXT,
    backlog_id TEXT,
    backlog_url TEXT,
    model TEXT,
    session_cost_usd REAL NOT NULL,
    input_tokens INTEGER NOT NULL DEFAULT 0,
    output_tokens INTEGER NOT NULL DEFAULT 0,
    cache_creation_input_tokens INTEGER NOT NULL DEFAULT 0,
    cache_read_input_tokens INTEGER NOT NULL DEFAULT 0,
    blended_total_tokens INTEGER
);

CREATE INDEX telemetry_cost_next_step_key_idx
    ON telemetry_cost (next_step_key);

INSERT INTO telemetry_cost
    (session_id, recorded_at_epoch_s, next_step_key, next_step_title,
     ccd_id, github_issue_number, backlog_provider, backlog_kind, backlog_id,
     backlog_url, model, session_cost_usd, input_tokens, output_tokens,
     cache_creation_input_tokens, cache_read_input_tokens, blended_total_tokens)
VALUES
    ('ses_1', 1000, 'handoff_title:seeded', 'Next Session: Runtime cleanup',
     42, 142, 'github-issues', 'issue', '142',
     'https://example.test/issues/142', 'gpt-5', 1.50, 100, 50, 25, 10, 185);
"#,
        )
        .unwrap();
        conn.pragma_update(None, "user_version", 14).unwrap();

        migrate(&conn, None).unwrap();

        assert!(!table_has_column(&conn, "telemetry_cost", "ccd_id").unwrap());
        assert!(!table_has_column(&conn, "telemetry_cost", "github_issue_number").unwrap());
        assert!(!table_has_column(&conn, "telemetry_cost", "backlog_provider").unwrap());
        assert!(!table_has_column(&conn, "telemetry_cost", "backlog_kind").unwrap());
        assert!(!table_has_column(&conn, "telemetry_cost", "backlog_id").unwrap());
        assert!(!table_has_column(&conn, "telemetry_cost", "backlog_url").unwrap());

        let row: (String, String, String, f64) = conn
            .query_row(
                "SELECT next_step_key, next_step_title, model, session_cost_usd
                 FROM telemetry_cost WHERE session_id = 'ses_1'",
                [],
                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
            )
            .unwrap();
        assert_eq!(row.0, "handoff_title:seeded");
        assert_eq!(row.1, "Next Session: Runtime cleanup");
        assert_eq!(row.2, "gpt-5");
        assert!((row.3 - 1.5).abs() < f64::EPSILON);
    }

    // ── M4(c): memory_evidence.scope CHECK drop + fail-closed gate ───────

    fn seed_v15_memory_evidence(conn: &Connection) {
        conn.execute_batch(
            r#"
CREATE TABLE memory_evidence (
    id TEXT PRIMARY KEY,
    scope TEXT NOT NULL CHECK (scope IN ('workspace', 'work_stream', 'project', 'profile', 'pod', 'project_truth')),
    entry_type TEXT NOT NULL CHECK (entry_type IN ('rule', 'constraint', 'heuristic', 'observation', 'attempt')),
    source_kind TEXT NOT NULL CHECK (source_kind IN ('transcript', 'session', 'event_stream', 'hook_output', 'log', 'document')),
    summary TEXT NOT NULL,
    summary_digest TEXT NOT NULL,
    observed_at_epoch_s INTEGER NOT NULL,
    actor_id TEXT,
    session_id TEXT,
    source_ref TEXT,
    host TEXT,
    host_hook TEXT,
    host_session_id TEXT,
    host_run_id TEXT,
    host_task_id TEXT,
    provider_name TEXT,
    provider_ref TEXT,
    extracted INTEGER NOT NULL DEFAULT 0,
    extracted_candidate_id TEXT,
    extracted_at_epoch_s INTEGER
);

CREATE INDEX memory_evidence_extracted_idx
    ON memory_evidence (extracted, observed_at_epoch_s);
"#,
        )
        .unwrap();
    }

    fn insert_evidence(conn: &Connection, id: &str, scope: &str) {
        conn.execute(
            "INSERT INTO memory_evidence
                (id, scope, entry_type, source_kind, summary, summary_digest,
                 observed_at_epoch_s)
             VALUES (?1, ?2, 'rule', 'transcript', 'x', 'd', 1000)",
            rusqlite::params![id, scope],
        )
        .unwrap();
    }

    #[test]
    fn migrate_v15_to_v16_refuses_when_pod_rows_exist() {
        let conn = Connection::open_in_memory().unwrap();
        seed_v15_memory_evidence(&conn);
        insert_evidence(&conn, "ev_1", "pod");

        let before_sql: String = conn
            .query_row(
                "SELECT sql FROM sqlite_master WHERE type='table' AND name='memory_evidence'",
                [],
                |row| row.get(0),
            )
            .unwrap();

        let err = migrate_v15_to_v16_with_pods_root(&conn, None).expect_err("gate must refuse");
        let msg = err.to_string();
        assert!(msg.contains("scope='pod'"), "got: {msg}");
        assert!(
            msg.contains("ccd migrate from-pod-layout"),
            "error must name the migration tool, got: {msg}"
        );

        // Prior schema bytes untouched — the CHECK enum still admits 'pod'.
        let after_sql: String = conn
            .query_row(
                "SELECT sql FROM sqlite_master WHERE type='table' AND name='memory_evidence'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(before_sql, after_sql);
    }

    #[test]
    fn migrate_v15_to_v16_refuses_when_pod_dirs_lack_migrated_md() {
        let temp = tempfile::tempdir().unwrap();
        let pods_root = temp.path().join("pods");
        std::fs::create_dir_all(pods_root.join("alpha")).unwrap();
        std::fs::create_dir_all(pods_root.join("beta")).unwrap();
        // Both dirs are real pods (they carry pod markers); alpha has a
        // migration marker, beta does not.
        std::fs::write(pods_root.join("alpha/pod.toml"), "").unwrap();
        std::fs::write(pods_root.join("beta/pod.toml"), "").unwrap();
        std::fs::write(pods_root.join("alpha/MIGRATED.md"), "ok").unwrap();

        let conn = Connection::open_in_memory().unwrap();
        seed_v15_memory_evidence(&conn);

        let err = migrate_v15_to_v16_with_pods_root(&conn, Some(&pods_root))
            .expect_err("gate must refuse");
        let msg = err.to_string();
        assert!(
            msg.contains("beta"),
            "error must name the offending pod: {msg}"
        );
        assert!(
            !msg.contains("alpha"),
            "migrated pod must not be listed: {msg}"
        );
        assert!(msg.contains("ccd migrate from-pod-layout"), "got: {msg}");

        // CHECK enum still admits 'pod' — schema untouched on refuse.
        assert!(memory_evidence_check_allows_pod(&conn).unwrap());
    }

    #[test]
    fn migrate_v15_to_v16_succeeds_when_gate_passes() {
        let temp = tempfile::tempdir().unwrap();
        // pods_root does not exist — equivalent to a clean host.
        let pods_root = temp.path().join("pods");

        let conn = Connection::open_in_memory().unwrap();
        seed_v15_memory_evidence(&conn);
        insert_evidence(&conn, "ev_keep", "workspace");

        migrate_v15_to_v16_with_pods_root(&conn, Some(&pods_root)).unwrap();

        // Row survived.
        let surviving: String = conn
            .query_row(
                "SELECT scope FROM memory_evidence WHERE id = 'ev_keep'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(surviving, "workspace");

        // CHECK no longer admits 'pod'.
        assert!(!memory_evidence_check_allows_pod(&conn).unwrap());
        let rejected = conn.execute(
            "INSERT INTO memory_evidence
                (id, scope, entry_type, source_kind, summary, summary_digest,
                 observed_at_epoch_s)
             VALUES ('ev_bad', 'pod', 'rule', 'transcript', 'x', 'd', 1000)",
            [],
        );
        assert!(
            rejected.is_err(),
            "post-migration CHECK must reject scope='pod'"
        );

        // Index survived the rewrite.
        let idx_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM sqlite_master
                 WHERE type='index' AND name='memory_evidence_extracted_idx'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(idx_count, 1);
    }

    #[test]
    fn migrate_v15_to_v16_succeeds_when_all_pods_migrated() {
        let temp = tempfile::tempdir().unwrap();
        let pods_root = temp.path().join("pods");
        std::fs::create_dir_all(pods_root.join("alpha")).unwrap();
        std::fs::create_dir_all(pods_root.join("beta")).unwrap();
        // Both dirs carry pod markers so the gate considers them.
        std::fs::write(pods_root.join("alpha/pod.toml"), "").unwrap();
        std::fs::write(pods_root.join("beta/pod.toml"), "").unwrap();
        std::fs::write(pods_root.join("alpha/MIGRATED.md"), "ok").unwrap();
        std::fs::write(pods_root.join("beta/MIGRATED.md"), "ok").unwrap();

        let conn = Connection::open_in_memory().unwrap();
        seed_v15_memory_evidence(&conn);

        migrate_v15_to_v16_with_pods_root(&conn, Some(&pods_root)).unwrap();
        assert!(!memory_evidence_check_allows_pod(&conn).unwrap());
    }

    #[test]
    fn migrate_v15_to_v16_ignores_foreign_dirs_without_pod_markers() {
        // A directory under `~/.ccd/pods/` that has none of the real-pod
        // markers (pod.toml, machine.toml, memory.md, policy.md, presence/,
        // repos/) is foreign to the migration tool and must not block the
        // schema bump.
        let temp = tempfile::tempdir().unwrap();
        let pods_root = temp.path().join("pods");
        std::fs::create_dir_all(pods_root.join("legacy-backup")).unwrap();
        std::fs::write(pods_root.join("legacy-backup/notes.txt"), "junk").unwrap();
        std::fs::create_dir_all(pods_root.join("scratch/nested")).unwrap();

        let conn = Connection::open_in_memory().unwrap();
        seed_v15_memory_evidence(&conn);

        migrate_v15_to_v16_with_pods_root(&conn, Some(&pods_root)).unwrap();
        assert!(!memory_evidence_check_allows_pod(&conn).unwrap());
    }

    #[test]
    fn migrate_v15_to_v16_flags_real_pods_alongside_foreign_dirs() {
        // A real pod (carrying pod markers but lacking MIGRATED.md) must
        // still block, and the foreign dir next to it must be silently
        // ignored rather than listed as an un-migrated pod.
        let temp = tempfile::tempdir().unwrap();
        let pods_root = temp.path().join("pods");
        std::fs::create_dir_all(pods_root.join("realpod")).unwrap();
        std::fs::write(pods_root.join("realpod/machine.toml"), "").unwrap();
        std::fs::create_dir_all(pods_root.join("random-backup")).unwrap();
        std::fs::write(pods_root.join("random-backup/data.bin"), "junk").unwrap();

        let conn = Connection::open_in_memory().unwrap();
        seed_v15_memory_evidence(&conn);

        let err = migrate_v15_to_v16_with_pods_root(&conn, Some(&pods_root))
            .expect_err("real pod without MIGRATED.md must still block");
        let msg = err.to_string();
        assert!(msg.contains("realpod"), "got: {msg}");
        assert!(
            !msg.contains("random-backup"),
            "foreign dir must not be reported: {msg}"
        );
    }

    #[test]
    fn is_pod_dir_recognizes_each_marker() {
        for marker in POD_MARKER_NAMES {
            let temp = tempfile::tempdir().unwrap();
            let pod = temp.path().join("candidate");
            std::fs::create_dir_all(&pod).unwrap();
            let marker_path = pod.join(marker);
            if *marker == "presence" || *marker == "repos" {
                std::fs::create_dir_all(&marker_path).unwrap();
            } else {
                std::fs::write(&marker_path, "").unwrap();
            }
            assert!(is_pod_dir(&pod), "marker {marker} must count as a pod");
        }

        let temp = tempfile::tempdir().unwrap();
        let pod = temp.path().join("not-a-pod");
        std::fs::create_dir_all(&pod).unwrap();
        std::fs::write(pod.join("README.txt"), "").unwrap();
        assert!(
            !is_pod_dir(&pod),
            "dir without markers must not count as a pod"
        );
    }

    #[test]
    fn migrate_v15_to_v16_is_noop_when_memory_evidence_absent() {
        let conn = Connection::open_in_memory().unwrap();
        // No table created. Migration must succeed without touching the DB.
        migrate_v15_to_v16_with_pods_root(&conn, None).unwrap();
    }

    #[test]
    fn full_migrate_chain_from_v11_drops_pod_from_check() {
        // Seeds a v11-style DB (via the v11→v12 path) with clean state, then
        // drives the full migrate() chain to verify the v15→v16 step runs
        // alongside the earlier migrations.
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            r#"
CREATE TABLE handoff (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    title TEXT NOT NULL DEFAULT '',
    immediate_actions TEXT NOT NULL DEFAULT '[]',
    completed_state TEXT NOT NULL DEFAULT '[]',
    operational_guardrails TEXT NOT NULL DEFAULT '[]',
    key_files TEXT NOT NULL DEFAULT '[]',
    definition_of_done TEXT NOT NULL DEFAULT '[]',
    revision INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE session (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 4,
    started_at_epoch_s INTEGER NOT NULL,
    last_started_at_epoch_s INTEGER NOT NULL,
    start_count INTEGER NOT NULL DEFAULT 1,
    session_id TEXT,
    mode TEXT NOT NULL DEFAULT 'general',
    owner_kind TEXT,
    owner_id TEXT,
    supervisor_id TEXT,
    lease_ttl_secs INTEGER,
    last_heartbeat_at_epoch_s INTEGER,
    revision INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE execution_gates (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    schema_version INTEGER NOT NULL DEFAULT 1,
    seeded_from TEXT,
    gates TEXT NOT NULL DEFAULT '[]',
    revision INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE escalation (
    id TEXT PRIMARY KEY,
    kind TEXT NOT NULL,
    reason TEXT NOT NULL,
    created_at_epoch_s INTEGER NOT NULL,
    session_id TEXT
);

CREATE TABLE projection_metadata (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    observed_at_epoch_s INTEGER NOT NULL,
    source_fingerprint TEXT NOT NULL,
    projection_digests TEXT,
    tool_surface_fingerprint TEXT,
    session_id TEXT
);

CREATE TABLE session_activity (
    session_id TEXT NOT NULL,
    started_at_epoch_s INTEGER NOT NULL,
    last_active_at_epoch_s INTEGER NOT NULL
);

CREATE TABLE telemetry_cost (
    session_id TEXT PRIMARY KEY,
    recorded_at_epoch_s INTEGER NOT NULL,
    next_step_key TEXT NOT NULL DEFAULT '',
    next_step_title TEXT,
    model TEXT,
    session_cost_usd REAL NOT NULL,
    input_tokens INTEGER NOT NULL DEFAULT 0,
    output_tokens INTEGER NOT NULL DEFAULT 0,
    cache_creation_input_tokens INTEGER NOT NULL DEFAULT 0,
    cache_read_input_tokens INTEGER NOT NULL DEFAULT 0,
    blended_total_tokens INTEGER
);

CREATE INDEX telemetry_cost_next_step_key_idx
    ON telemetry_cost (next_step_key);

CREATE TABLE memory_op_queue (
    id TEXT PRIMARY KEY,
    command TEXT NOT NULL,
    request_fingerprint TEXT NOT NULL,
    plan_json TEXT NOT NULL,
    staged_at_epoch_s INTEGER NOT NULL,
    updated_at_epoch_s INTEGER NOT NULL,
    actor_id TEXT,
    session_id TEXT,
    reconciled INTEGER NOT NULL DEFAULT 0,
    outcome TEXT,
    authored_entry_ids TEXT NOT NULL DEFAULT '[]',
    authored_target_path TEXT,
    authored_source_path TEXT,
    snapshot_json TEXT
);
"#,
        )
        .unwrap();
        conn.pragma_update(None, "user_version", 11).unwrap();

        migrate(&conn, None).unwrap();

        let version: u32 = conn
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version, CURRENT_VERSION);
        assert!(!memory_evidence_check_allows_pod(&conn).unwrap());
    }

    #[test]
    fn migrate_v15_to_v16_refuses_stale_marker_over_live_machine_toml() {
        let temp = tempfile::tempdir().unwrap();
        let pods_root = temp.path().join("pods");
        std::fs::create_dir_all(pods_root.join("stale")).unwrap();
        // Pod carries the marker, but a live `machine.toml` source still
        // sits alongside it — the marker is untrustworthy.
        std::fs::write(pods_root.join("stale/pod.toml"), "").unwrap();
        std::fs::write(pods_root.join("stale/machine.toml"), "").unwrap();
        std::fs::write(pods_root.join("stale/MIGRATED.md"), "ok").unwrap();

        let conn = Connection::open_in_memory().unwrap();
        seed_v15_memory_evidence(&conn);

        let err = migrate_v15_to_v16_with_pods_root(&conn, Some(&pods_root))
            .expect_err("stale marker must block the bump");
        let msg = err.to_string();
        assert!(msg.contains("stale"), "pod name must appear: {msg}");
        assert!(
            msg.contains("machine.toml"),
            "pending source must be named: {msg}"
        );
        assert!(msg.contains("ccd migrate from-pod-layout"), "got: {msg}");
        // Schema untouched on refuse.
        assert!(memory_evidence_check_allows_pod(&conn).unwrap());
    }

    #[test]
    fn migrate_v15_to_v16_refuses_stale_marker_over_pending_presence_json() {
        let temp = tempfile::tempdir().unwrap();
        let pods_root = temp.path().join("pods");
        let pod = pods_root.join("stale");
        std::fs::create_dir_all(pod.join("presence")).unwrap();
        std::fs::write(pod.join("pod.toml"), "").unwrap();
        std::fs::write(pod.join("presence/laptop.json"), "{}").unwrap();
        std::fs::write(pod.join("MIGRATED.md"), "ok").unwrap();

        let conn = Connection::open_in_memory().unwrap();
        seed_v15_memory_evidence(&conn);

        let err = migrate_v15_to_v16_with_pods_root(&conn, Some(&pods_root))
            .expect_err("presence/*.json must block a stale marker");
        let msg = err.to_string();
        assert!(msg.contains("presence/laptop.json"), "got: {msg}");
    }

    #[test]
    fn migrate_v15_to_v16_accepts_marker_over_inert_legacy_files() {
        // A migrated pod may still carry non-source files (memory.md, policy.md,
        // pod.toml) as legacy artifacts preserved by the migration tool. Those
        // do NOT invalidate MIGRATED.md — only machine.toml and presence/*.json
        // do.
        let temp = tempfile::tempdir().unwrap();
        let pod = temp.path().join("pods/migrated");
        std::fs::create_dir_all(&pod).unwrap();
        std::fs::write(pod.join("pod.toml"), "").unwrap();
        std::fs::write(pod.join("memory.md"), "stale memory").unwrap();
        std::fs::write(pod.join("policy.md"), "stale policy").unwrap();
        std::fs::write(pod.join("MIGRATED.md"), "ok").unwrap();

        let conn = Connection::open_in_memory().unwrap();
        seed_v15_memory_evidence(&conn);

        migrate_v15_to_v16_with_pods_root(&conn, Some(&temp.path().join("pods"))).unwrap();
        assert!(!memory_evidence_check_allows_pod(&conn).unwrap());
    }

    #[test]
    fn migrate_v15_to_v16_refuses_leftover_v15_table_from_prior_attempt() {
        // Simulate an interrupted prior migration: memory_evidence was renamed
        // to memory_evidence_v15 but the rewrite never completed. We must not
        // silently advance user_version; we must surface the partial state.
        let conn = Connection::open_in_memory().unwrap();
        seed_v15_memory_evidence(&conn);
        conn.execute_batch("ALTER TABLE memory_evidence RENAME TO memory_evidence_v15;")
            .unwrap();

        let err = migrate_v15_to_v16_with_pods_root(&conn, None)
            .expect_err("leftover v15 table must block the bump");
        assert!(
            err.to_string().contains("memory_evidence_v15"),
            "error must name the leftover table: {err}"
        );
    }

    #[test]
    fn migrate_v15_to_v16_rolls_back_ddl_on_mid_migration_failure() {
        // Force a failure during data copy by putting a row in v15 whose
        // `entry_type` does not match the v16 CHECK (we mutate the v15 table
        // to drop its own CHECK so the row can exist there, but v16 still
        // rejects it). Verify the rollback leaves the pre-migration table
        // intact — no leftover `memory_evidence_v15`, no half-written v16.
        let conn = Connection::open_in_memory().unwrap();
        seed_v15_memory_evidence(&conn);

        // Replace the v15 table with an unchecked shape so we can seed an
        // out-of-enum `entry_type`. Then rename it back so the migration
        // picks it up as the canonical memory_evidence.
        conn.execute_batch(
            r#"
DROP INDEX IF EXISTS memory_evidence_extracted_idx;
DROP TABLE memory_evidence;
CREATE TABLE memory_evidence (
    id TEXT PRIMARY KEY,
    scope TEXT NOT NULL,
    entry_type TEXT NOT NULL,
    source_kind TEXT NOT NULL,
    summary TEXT NOT NULL,
    summary_digest TEXT NOT NULL,
    observed_at_epoch_s INTEGER NOT NULL,
    actor_id TEXT, session_id TEXT, source_ref TEXT, host TEXT,
    host_hook TEXT, host_session_id TEXT, host_run_id TEXT,
    host_task_id TEXT, provider_name TEXT, provider_ref TEXT,
    extracted INTEGER NOT NULL DEFAULT 0,
    extracted_candidate_id TEXT, extracted_at_epoch_s INTEGER
);
INSERT INTO memory_evidence
    (id, scope, entry_type, source_kind, summary, summary_digest, observed_at_epoch_s)
VALUES ('ev_bad', 'workspace', 'not_a_real_entry_type', 'transcript', 'x', 'd', 1);
"#,
        )
        .unwrap();

        let result = migrate_v15_to_v16_with_pods_root(&conn, None);
        assert!(result.is_err(), "migration must fail on invalid entry_type");

        // The DDL rollback must leave the original table in place and must
        // not strand a memory_evidence_v15.
        assert!(table_exists(&conn, "memory_evidence").unwrap());
        assert!(!table_exists(&conn, "memory_evidence_v15").unwrap());
        let row_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_evidence", [], |row| row.get(0))
            .unwrap();
        assert_eq!(row_count, 1, "pre-migration row must survive rollback");
    }

    #[test]
    fn migrate_v0_repair_runs_gate_b_against_unmigrated_pods() {
        // A touched / empty state.db at user_version=0 runs through
        // `repair_zero_version_schema`, which applies SCHEMA_CURRENT (v16
        // memory_evidence with the restricted CHECK). Gate (b) must still
        // fire on that path so the operator cannot bypass the precondition
        // by presenting an empty DB.
        let temp = tempfile::tempdir().unwrap();
        let pods_root = temp.path().join("pods");
        std::fs::create_dir_all(pods_root.join("pending")).unwrap();
        std::fs::write(pods_root.join("pending/pod.toml"), "").unwrap();

        let conn = Connection::open_in_memory().unwrap();
        // user_version stays 0 and no tables exist — simulates a touched DB.

        let err = migrate(&conn, Some(&pods_root)).expect_err("v0 repair path must honor gate (b)");
        assert!(err.to_string().contains("pending"), "got: {err}");
        // user_version must not advance past 0 on refusal.
        let version: u32 = conn
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(
            version, 0,
            "bump must be rolled back to pre-migration state"
        );
        // Atomicity: SCHEMA_CURRENT must NOT have been applied. The DB must
        // be as the caller left it — no memory_evidence table appearing out
        // of thin air just because the gate noticed a dirty pods tree.
        let table_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            table_count, 0,
            "refused v0 migration must leave the DB byte-for-byte untouched"
        );
    }

    #[test]
    fn migrate_v0_repair_allows_clean_environment() {
        let temp = tempfile::tempdir().unwrap();
        // pods_root absent — represents a truly clean host.
        let pods_root = temp.path().join("pods");

        let conn = Connection::open_in_memory().unwrap();
        migrate(&conn, Some(&pods_root)).unwrap();
        let version: u32 = conn
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version, CURRENT_VERSION);
        assert!(!memory_evidence_check_allows_pod(&conn).unwrap());
    }
}