crtx 0.1.1

CLI for the Cortex supervisory memory substrate.
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
//! CLI tests for schema-version gates.

use std::path::{Path, PathBuf};
use std::process::Command;

use chrono::{TimeZone, Utc};
use cortex_core::{
    Event, EventId, EventSource, EventType, KeyLifecycleState, SchemaMigrationV1ToV2Payload,
    TrustTier,
};
use cortex_ledger::{
    append_policy_decision_test_allow, audit::verify_schema_migration_v1_to_v2_boundary,
    schema_migration_v1_to_v2_policy_decision_test_allow, JsonlLog,
};
use cortex_store::migrate::apply_pending;
use cortex_store::migrate_v2::{dry_run_plan, fixture_verification_result_hash};
use cortex_store::repo::{AuthorityRepo, KeyTimelineRecord, PrincipalTimelineRecord};
use ed25519_dalek::{Signer, SigningKey};
use rusqlite::Connection;

fn cortex_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_cortex"))
}

fn fixtures_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
}

fn run_in(cwd: &Path, args: &[&str]) -> std::process::Output {
    let data_dir = cwd.join("xdg").join("cortex");
    Command::new(cortex_bin())
        .current_dir(cwd)
        .env("CORTEX_DATA_DIR", &data_dir)
        .env("XDG_DATA_HOME", cwd.join("xdg"))
        .env("HOME", cwd)
        .env("APPDATA", cwd.join("appdata"))
        .env("LOCALAPPDATA", cwd.join("localappdata"))
        .args(args)
        .output()
        .expect("spawn cortex")
}

fn assert_exit(out: &std::process::Output, expected: i32) {
    let code = out.status.code().expect("process exited via signal");
    assert_eq!(
        code,
        expected,
        "expected exit {expected}, got {code}\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
}

/// Post-cutover readiness: the schema v2 atomic commit (ADR 0018) flipped every
/// `default_v2_*` flag to ready. After Gate 5 punch list #17 landed the
/// migration authority root attestation contributor, `unattended_migrate`
/// reports `requires_operator_attestation` — the flag is supported only when
/// paired with a valid `--operator-attestation <PATH>` envelope.
fn assert_cutover_readiness_ready(output: &str) {
    for field in [
        "default_v2_persistence_ready=true",
        "default_v2_write_enabled=true",
        "default_v2_cutover_ready=true",
        "cutover_readiness=ready",
        "cutover_readiness_missing_gates=0",
        "unattended_migrate_supported=requires_operator_attestation",
    ] {
        assert!(output.contains(field), "output missing {field}: {output}");
    }
}

fn has_column(pool: &Connection, table: &str, column: &str) -> bool {
    let mut stmt = pool
        .prepare(&format!("PRAGMA table_info({table});"))
        .expect("prepare table_info");
    let rows = stmt
        .query_map([], |row| row.get::<_, String>(1))
        .expect("query table_info");

    for row in rows {
        if row.expect("column row") == column {
            return true;
        }
    }
    false
}

fn has_table(pool: &Connection, table: &str) -> bool {
    pool.query_row(
        "SELECT EXISTS (
            SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1
        );",
        [table],
        |row| row.get::<_, bool>(0),
    )
    .expect("query table existence")
}

fn table_count(pool: &Connection, table: &str) -> u64 {
    let sql = format!("SELECT COUNT(*) FROM {table};");
    pool.query_row(&sql, [], |row| row.get(0))
        .expect("query table count")
}

fn stdout_value<'a>(stdout: &'a str, key: &str) -> &'a str {
    let prefix = format!("{key}=");
    stdout
        .lines()
        .find_map(|line| line.strip_prefix(&prefix))
        .unwrap_or_else(|| panic!("stdout missing {key}: {stdout}"))
}

fn init_layout(tmp: &Path) -> (PathBuf, PathBuf) {
    let out = run_in(tmp, &["init"]);
    assert_exit(&out, 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    let db_line = stdout
        .lines()
        .find(|line| line.starts_with("cortex init: db"))
        .expect("init stdout includes db path");
    let path = db_line
        .split_once('=')
        .expect("db line has equals")
        .1
        .trim()
        .split_once(" (")
        .expect("db line has status suffix")
        .0;
    let event_log_line = stdout
        .lines()
        .find(|line| line.starts_with("cortex init: event_log"))
        .expect("init stdout includes event log path");
    let event_log_path = event_log_line
        .split_once('=')
        .expect("event_log line has equals")
        .1
        .trim()
        .split_once(" (")
        .expect("event_log line has status suffix")
        .0;
    (PathBuf::from(path), PathBuf::from(event_log_path))
}

fn init(tmp: &Path) -> PathBuf {
    init_layout(tmp).0
}

/// Phase 2.6 closure: seed the operator-key timeline for the
/// `fixture-operator-key` id (the same id
/// [`write_valid_operator_attestation`] pins into the envelope) so
/// `cortex migrate v2 --operator-attestation` passes the durable
/// timeline revalidation gate at `minimum_trust_tier = Operator`.
fn seed_migrate_operator_authority(db: &Path) {
    let pool = Connection::open(db).expect("open initialized sqlite db");
    apply_pending(&pool).expect("apply migrations");
    let repo = AuthorityRepo::new(&pool);
    let effective_at = Utc.with_ymd_and_hms(2026, 1, 1, 12, 0, 1).unwrap();
    repo.append_principal_state(
        &PrincipalTimelineRecord {
            principal_id: "operator-principal".into(),
            trust_tier: TrustTier::Operator,
            effective_at,
            trust_review_due_at: None,
            removed_at: None,
            audit_ref: None,
        },
        &cortex_store::repo::authority::principal_state_policy_decision_test_allow(),
    )
    .expect("append operator trust state");
    repo.append_key_state(
        &KeyTimelineRecord {
            key_id: "fixture-operator-key".into(),
            principal_id: "operator-principal".into(),
            state: KeyLifecycleState::Active,
            effective_at,
            reason: None,
            audit_ref: None,
        },
        &cortex_store::repo::authority::key_state_policy_decision_test_allow(),
    )
    .expect("append active operator key state");
}

/// Revoke the migrate-v2 fixture key effective at `effective_at`.
/// Used by Phase 2.6 refusal tests for the migration boundary.
fn revoke_migrate_operator_authority(db: &Path, effective_at: chrono::DateTime<Utc>) {
    let pool = Connection::open(db).expect("open initialized sqlite db");
    apply_pending(&pool).expect("apply migrations");
    AuthorityRepo::new(&pool)
        .append_key_state(
            &KeyTimelineRecord {
                key_id: "fixture-operator-key".into(),
                principal_id: "operator-principal".into(),
                state: KeyLifecycleState::Revoked,
                effective_at,
                reason: Some("test revocation".into()),
                audit_ref: None,
            },
            &cortex_store::repo::authority::key_state_policy_decision_test_allow(),
        )
        .expect("append revoked operator key state");
}

fn ingest_minimal_session(tmp: &Path) {
    let session = fixtures_dir().join("session-minimal.json");
    let out = run_in(tmp, &["ingest", session.to_str().unwrap()]);
    assert_exit(&out, 0);
}

fn write_valid_backup_manifest(path: &Path) {
    let dir = path.parent().expect("backup manifest has parent");
    std::fs::write(dir.join("state.sqlite"), "sqlite backup placeholder")
        .expect("write sqlite backup artifact");
    std::fs::write(dir.join("events.jsonl"), "jsonl backup placeholder")
        .expect("write jsonl backup artifact");
    std::fs::write(
        path,
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"state.sqlite","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z","table_row_counts":{"events":0,"traces":0,"episodes":0,"memories":0}}"#,
    )
    .expect("write backup manifest");
}

fn generate_backup_manifest(tmp: &Path) -> PathBuf {
    let output = tmp.join("backup-bundle");
    let out = run_in(tmp, &["backup", "--output", output.to_str().unwrap()]);
    assert_exit(&out, 0);
    output.join("BACKUP_MANIFEST")
}

/// Deterministic Ed25519 signing key for tests of the operator-attestation
/// envelope. Same shape as `cortex-core::InMemoryAttestor::from_seed`.
fn fixture_operator_signing_key() -> SigningKey {
    SigningKey::from_bytes(&[0x07u8; 32])
}

fn lowercase_hex(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        out.push_str(&format!("{b:02x}"));
    }
    out
}

/// Run `cortex migrate v2 --dry-run` and pull the boundary preflight triple
/// out of stdout so the test can sign an attestation envelope that matches
/// what the cutover path will compute.
fn dry_run_boundary_preflight(tmp: &Path) -> (String, String, String) {
    let out = run_in(tmp, &["migrate", "v2", "--dry-run"]);
    assert_exit(&out, 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    let head = stdout_value(&stdout, "boundary_previous_v1_head_hash").to_string();
    let script = stdout_value(&stdout, "migration_script_digest").to_string();
    let fixture = stdout_value(&stdout, "fixture_verification_result_hash").to_string();
    (head, script, fixture)
}

/// Build the same canonical signing input the CLI builds for an operator
/// attestation envelope (see `cmd::migrate::operator_attestation_signing_input`).
fn operator_attestation_test_signing_input(
    schema_version: u16,
    purpose: &str,
    key_id: &str,
    signed_at_rfc3339: &str,
    previous_v1_head_hash: &str,
    migration_script_digest: &str,
    fixture_verification_result_hash: &str,
) -> Vec<u8> {
    const DOMAIN_TAG: u8 = 0x20;
    let mut out = Vec::new();
    out.push(DOMAIN_TAG);
    out.extend_from_slice(&schema_version.to_be_bytes());
    for field in [
        purpose,
        key_id,
        signed_at_rfc3339,
        previous_v1_head_hash,
        migration_script_digest,
        fixture_verification_result_hash,
    ] {
        out.extend_from_slice(&(field.len() as u64).to_be_bytes());
        out.extend_from_slice(field.as_bytes());
    }
    out
}

/// Write a valid Ed25519-signed operator attestation envelope to `path` that
/// authorises the v1 -> v2 boundary represented by `previous_v1_head_hash`,
/// `migration_script_digest`, and `fixture_verification_result_hash`.
fn write_valid_operator_attestation(
    path: &Path,
    previous_v1_head_hash: &str,
    migration_script_digest: &str,
    fixture_verification_result_hash: &str,
) {
    let signing_key = fixture_operator_signing_key();
    let verifying_key = signing_key.verifying_key();
    let operator_key_id = "fixture-operator-key";
    let purpose = "cortex.schema_migration.v1_to_v2";
    let schema_version: u16 = 1;
    let signed_at = Utc::now().to_rfc3339();
    let signing_input = operator_attestation_test_signing_input(
        schema_version,
        purpose,
        operator_key_id,
        &signed_at,
        previous_v1_head_hash,
        migration_script_digest,
        fixture_verification_result_hash,
    );
    let signature = signing_key.sign(&signing_input);

    let envelope = serde_json::json!({
        "schema_version": schema_version,
        "purpose": purpose,
        "operator_verifying_key_hex": lowercase_hex(verifying_key.as_bytes()),
        "operator_key_id": operator_key_id,
        "signed_at": signed_at,
        "boundary": {
            "previous_v1_head_hash": previous_v1_head_hash,
            "migration_script_digest": migration_script_digest,
            "fixture_verification_result_hash": fixture_verification_result_hash,
        },
        "signature_hex": lowercase_hex(&signature.to_bytes()),
    });
    std::fs::write(path, serde_json::to_string_pretty(&envelope).unwrap())
        .expect("write operator attestation envelope");
}

fn tamper_last_jsonl_event_payload(path: &Path) {
    let raw = std::fs::read_to_string(path).expect("read event log");
    let mut rows: Vec<serde_json::Value> = raw
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| serde_json::from_str(line).expect("parse signed row"))
        .collect();
    let last_row = rows.last_mut().expect("event log has rows");
    let event = if last_row.get("event").is_some() {
        last_row.get_mut("event").expect("nested event exists")
    } else {
        last_row
    };
    let payload = event
        .get_mut("payload")
        .expect("last event row has payload");
    *payload = serde_json::json!({"tampered_after_boundary": true});

    let mut serialized = String::new();
    for row in rows {
        serialized.push_str(&serde_json::to_string(&row).expect("serialize signed row"));
        serialized.push('\n');
    }
    std::fs::write(path, serialized).expect("rewrite tampered event log");
}

fn append_post_boundary_schema_v2_event(path: &Path) {
    let mut log = JsonlLog::open(path).expect("open event log for post-boundary v2 append");
    let event = Event {
        id: EventId::new(),
        schema_version: 2,
        observed_at: "2026-05-04T23:00:00Z".parse().unwrap(),
        recorded_at: "2026-05-04T23:00:01Z".parse().unwrap(),
        source: EventSource::Tool {
            name: "schema-v2-fixture".into(),
        },
        event_type: EventType::ToolResult,
        trace_id: None,
        session_id: Some("s2-post-boundary".into()),
        domain_tags: vec!["schema".into(), "s2".into()],
        payload: serde_json::json!({
            "post_boundary_schema_v2": true,
            "fixture": "cli-audit-traversal"
        }),
        payload_hash: String::new(),
        prev_event_hash: None,
        event_hash: String::new(),
    };
    log.append(event, &append_policy_decision_test_allow())
        .expect("append post-boundary schema v2 row");
}

fn assert_backup_manifest_rejected_without_mutation(
    manifest_json: &str,
    expected_exit: i32,
    expected_stderr: &[&str],
) {
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    let manifest = tmp.path().join("backup-manifest.json");
    std::fs::write(&manifest, manifest_json).expect("write backup manifest");

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
        ],
    );

    assert_exit(&out, expected_exit);
    let stderr = String::from_utf8_lossy(&out.stderr);
    for expected in expected_stderr {
        assert!(stderr.contains(expected), "stderr: {stderr}");
    }
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "events"), events_before);
    // Post-cutover (ADR 0018): the default migration bundle adds the S2.9
    // expand columns at `apply_pending` time. The manifest rejection still
    // fires before any boundary-related mutation.
    assert!(has_column(&pool, "events", "source_attestation_json"));
}

#[test]
fn audit_verify_default_does_not_require_v1_to_v2_boundary() {
    let tmp = tempfile::tempdir().unwrap();
    init_layout(tmp.path());
    ingest_minimal_session(tmp.path());

    let out = run_in(tmp.path(), &["audit", "verify"]);

    assert_exit(&out, 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("audit verify:"), "stdout: {stdout}");
}

#[test]
fn audit_verify_requires_v1_to_v2_boundary_when_flagged() {
    let tmp = tempfile::tempdir().unwrap();
    init_layout(tmp.path());
    ingest_minimal_session(tmp.path());

    let out = run_in(
        tmp.path(),
        &["audit", "verify", "--require-v1-to-v2-boundary"],
    );

    assert_exit(&out, 4);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("schema_migration.v1_to_v2.boundary.missing"),
        "stderr: {stderr}"
    );
}

#[test]
fn audit_verify_require_v1_to_v2_boundary_passes_with_exactly_one_boundary() {
    let tmp = tempfile::tempdir().unwrap();
    let (_db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());

    let mut log = JsonlLog::open(&event_log_path).expect("open event log");
    let v1_head = log.head().expect("v1 head").to_string();
    log.append_schema_migration_v1_to_v2(
        SchemaMigrationV1ToV2Payload::new(v1_head, "script-digest", None, "fixture-digest"),
        &schema_migration_v1_to_v2_policy_decision_test_allow(),
    )
    .expect("append boundary");

    let out = run_in(
        tmp.path(),
        &["audit", "verify", "--require-v1-to-v2-boundary"],
    );

    assert_exit(&out, 0);
}

#[test]
fn audit_verify_require_v1_to_v2_boundary_rejects_duplicate_boundary_rows() {
    let tmp = tempfile::tempdir().unwrap();
    let (_db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());

    let mut log = JsonlLog::open(&event_log_path).expect("open event log");
    let v1_head = log.head().expect("v1 head").to_string();
    let first_boundary = log
        .append_schema_migration_v1_to_v2(
            SchemaMigrationV1ToV2Payload::new(v1_head, "script-digest", None, "fixture-digest"),
            &schema_migration_v1_to_v2_policy_decision_test_allow(),
        )
        .expect("append first boundary");
    log.append_schema_migration_v1_to_v2(
        SchemaMigrationV1ToV2Payload::new(first_boundary, "script-digest", None, "fixture-digest"),
        &schema_migration_v1_to_v2_policy_decision_test_allow(),
    )
    .expect("append duplicate boundary");

    let out = run_in(
        tmp.path(),
        &["audit", "verify", "--require-v1-to-v2-boundary"],
    );

    assert_exit(&out, 4);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("schema_migration.v1_to_v2.boundary.duplicate"),
        "stderr: {stderr}"
    );
}

#[test]
fn audit_verify_accepts_post_cutover_v2_current_event_wire_rows() {
    let tmp = tempfile::tempdir().unwrap();
    let (_db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());

    let mut log = JsonlLog::open(&event_log_path).expect("open event log");
    let v1_head = log.head().expect("v1 head").to_string();
    log.append_schema_migration_v1_to_v2(
        SchemaMigrationV1ToV2Payload::new(v1_head, "script-digest", None, "fixture-digest"),
        &schema_migration_v1_to_v2_policy_decision_test_allow(),
    )
    .expect("append boundary");

    let post_cutover = Event {
        id: EventId::new(),
        schema_version: 2,
        observed_at: chrono::Utc::now(),
        recorded_at: chrono::Utc::now(),
        source: EventSource::Runtime,
        event_type: EventType::ToolResult,
        trace_id: None,
        session_id: Some("lane-s2".into()),
        domain_tags: vec![],
        payload: serde_json::json!({
            "fixture": "post-cutover-v2",
            "expected": "verify"
        }),
        payload_hash: String::new(),
        prev_event_hash: None,
        event_hash: String::new(),
    };
    log.append(post_cutover, &append_policy_decision_test_allow())
        .expect("append unsupported v2 row");

    let out = run_in(tmp.path(), &["audit", "verify"]);

    assert_exit(&out, 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("0 failures"), "stdout: {stdout}");
}

#[test]
fn migrate_v2_dry_run_reports_plan_without_mutation() {
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    let migrations_before = table_count(&pool, "_migrations");

    let out = run_in(tmp.path(), &["migrate", "v2", "--dry-run"]);

    assert_exit(&out, 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("cortex migrate v2: dry-run ok"),
        "stdout: {stdout}"
    );
    assert!(
        stdout.contains("step=preflight_schema_v1"),
        "stdout: {stdout}"
    );
    assert!(
        stdout.contains("step=leave_schema_version_unchanged"),
        "stdout: {stdout}"
    );
    assert!(
        stdout.contains("boundary_event_kind=schema_migration.v1_to_v2"),
        "stdout: {stdout}"
    );
    assert!(
        stdout.contains("schema_version_target=2"),
        "stdout: {stdout}"
    );
    assert!(
        stdout.contains("boundary_previous_v1_head_hash="),
        "stdout: {stdout}"
    );
    assert!(
        stdout.contains("migration_script_digest=blake3:"),
        "stdout: {stdout}"
    );
    assert!(
        stdout.contains("fixture_verification_result_hash=blake3:"),
        "stdout: {stdout}"
    );
    let boundary_previous_v1_head_hash = stdout_value(&stdout, "boundary_previous_v1_head_hash");
    let fixture_verification_result_hash_stdout =
        stdout_value(&stdout, "fixture_verification_result_hash");
    assert_eq!(
        fixture_verification_result_hash_stdout.len(),
        "blake3:".len() + 64,
        "stdout: {stdout}"
    );
    let expected_fixture_verification_result_hash = fixture_verification_result_hash(
        &dry_run_plan(&pool).expect("dry-run plan after CLI dry-run"),
        boundary_previous_v1_head_hash,
    );
    assert_eq!(
        fixture_verification_result_hash_stdout, expected_fixture_verification_result_hash,
        "stdout digest must match store fixture verification helper"
    );
    assert!(
        stdout.contains("operator_attestation_mode=dry_run_not_collected"),
        "stdout: {stdout}"
    );
    assert!(
        stdout.contains("boundary_preflight_ready=true"),
        "stdout: {stdout}"
    );
    // Post-cutover (ADR 0018): the dry-run path reports readiness as ready but
    // still gates on `--backup-manifest` so it never auto-promotes.
    assert!(stdout.contains("cutover_authority=ok"), "stdout: {stdout}");
    assert!(
        stdout.contains("cutover_approved=false"),
        "stdout: {stdout}"
    );
    assert!(
        stdout.contains("cutover_guard=requires_backup_manifest"),
        "stdout: {stdout}"
    );
    assert_cutover_readiness_ready(&stdout);
    assert!(
        !stdout.contains("cutover_approved=true"),
        "stdout: {stdout}"
    );
    assert!(stdout.contains("no state was changed"), "stdout: {stdout}");

    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "events"), events_before);
    assert_eq!(table_count(&pool, "_migrations"), migrations_before);
    // After the cutover, `migration 003_schema_v2_expand` is part of the
    // default bundle. `apply_pending` (run before dry-run) already added the
    // S2.9 columns and side tables; the dry-run path is read-only and leaves
    // them alone.
    assert!(has_column(&pool, "events", "source_attestation_json"));
    assert!(has_table(&pool, "memory_session_uses"));
}

#[test]
fn migrate_v2_dry_run_requires_v1_event_head_for_boundary_preflight() {
    let tmp = tempfile::tempdir().unwrap();
    init(tmp.path());

    let out = run_in(tmp.path(), &["migrate", "v2", "--dry-run"]);

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("boundary preflight requires a current v1 event_chain_head"),
        "stderr: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");
}

#[test]
fn migrate_v2_dry_run_refuses_future_schema_rows() {
    // Post-cutover (ADR 0018, ADR 0033 §6): `SCHEMA_VERSION = 2` is the
    // running shape. A row with `schema_version = 3` is a *future* row this
    // binary cannot frame and must fail closed.
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    pool.execute(
        "INSERT INTO events (
            id, schema_version, observed_at, recorded_at, source_json, event_type,
            trace_id, session_id, domain_tags_json, payload_json, payload_hash,
            prev_event_hash, event_hash
        ) VALUES (
            'evt_future', 3, '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z',
            '{\"kind\":\"test\"}', 'test.event', NULL, NULL, '[]', '{}',
            'payload-hash', NULL, 'event-hash'
        );",
        [],
    )
    .expect("insert mismatched event");

    let out = run_in(tmp.path(), &["migrate", "v2", "--dry-run"]);

    assert_exit(&out, 4);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("cortex migrate v2: schema_version.events.matches_code"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("row evt_future has schema_version 3; expected 2"),
        "stderr: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");
}

#[test]
fn migrate_v2_without_dry_run_requires_backup_manifest() {
    // Post-cutover (ADR 0018): `cortex migrate v2` without `--dry-run` is now
    // a real cutover. It still fail-closes when invoked without a
    // `--backup-manifest`, but the rejection text now points operators at the
    // blessed pre-v2 backup contract rather than the pre-cutover
    // "not implemented" message.
    let tmp = tempfile::tempdir().unwrap();
    init(tmp.path());

    let out = run_in(tmp.path(), &["migrate", "v2"]);

    assert_exit(&out, 2);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("cutover requires --backup-manifest"),
        "stderr: {stderr}"
    );
    assert_cutover_readiness_ready(&stderr);
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");
}

#[test]
fn migrate_v2_rejects_backup_manifest_cutover_approval_fields_without_mutation() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    let migrations_before = table_count(&pool, "_migrations");
    let previous_v1_head = JsonlLog::open(&event_log_path)
        .expect("open event log")
        .head()
        .expect("v1 head")
        .to_string();
    std::fs::write(tmp.path().join("state.sqlite"), "sqlite backup placeholder")
        .expect("write sqlite backup artifact");
    std::fs::write(tmp.path().join("events.jsonl"), "jsonl backup placeholder")
        .expect("write jsonl backup artifact");
    let manifest = tmp.path().join("backup-manifest.json");
    std::fs::write(
        &manifest,
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"state.sqlite","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z","cutover_approved":true,"operator_approval":{"actor":"test"}}"#,
    )
    .expect("write forged approval backup manifest");

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("reserved cutover approval field `cutover_approved`")
            && stderr.contains("backup manifests cannot approve schema cutover"),
        "stderr: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "events"), events_before);
    assert_eq!(table_count(&pool, "_migrations"), migrations_before);
    // Post-cutover (ADR 0018): the schema v2 expand/backfill migration is in
    // the default bundle, so `apply_pending` already created the S2.9 columns
    // and side tables. The manifest rejection still fires before any boundary
    // mutation occurs.
    assert!(has_column(&pool, "events", "source_attestation_json"));
    assert!(has_table(&pool, "memory_session_uses"));
    let current_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("v1 head still present")
        .to_string();
    assert_eq!(current_head, previous_v1_head);
    let boundary_report =
        verify_schema_migration_v1_to_v2_boundary(&event_log_path, false).expect("boundary audit");
    assert!(boundary_report.ok(), "boundary report: {boundary_report:?}");
    assert!(boundary_report.boundary_rows.is_empty());
}

#[test]
fn migrate_v2_full_path_cuts_over_after_post_cutover_audit_dispatch() {
    // Schema v2 atomic cutover (ADR 0018): a valid backup manifest now drives
    // migrate v2 all the way through cutover. The boundary row is appended to
    // both JSONL and SQLite, the post-migrate manifest is written next to the
    // backup manifest, and the cutover-readiness fields all report ready.
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    assert_eq!(cortex_core::SCHEMA_VERSION, 2);
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let migrations_before = table_count(&pool, "_migrations");
    let previous_v1_head = JsonlLog::open(&event_log_path)
        .expect("open event log")
        .head()
        .expect("v1 head")
        .to_string();

    let missing_manifest = tmp.path().join("missing-backup-manifest.json");
    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            missing_manifest.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("backup manifest") && stderr.contains("was not found"),
        "stderr: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    let manifest = tmp.path().join("backup-manifest.json");
    write_valid_backup_manifest(&manifest);
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);
    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 0);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("operator_attestation_verified=true"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("stage=backup-preflight-ready status=ready"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("stage=expand/backfill status=ready"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("boundary_previous_v1_head_hash="),
        "stderr: {stderr}"
    );
    assert!(stderr.contains("boundary_event_hash="), "stderr: {stderr}");
    assert!(
        stderr.contains("boundary_event_kind=schema_migration.v1_to_v2"),
        "stderr: {stderr}"
    );
    assert!(stderr.contains("boundary_audit=ok"), "stderr: {stderr}");
    assert!(
        stderr.contains("post_migrate_mixed_chain_audit=ok"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("post_cutover_audit_dispatch=available"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("post_migrate_row_count_refusal=ok"),
        "stderr: {stderr}"
    );
    assert!(stderr.contains("cutover_authority=ok"), "stderr: {stderr}");
    assert!(stderr.contains("cutover_approved=true"), "stderr: {stderr}");
    assert!(
        stderr.contains("cutover_guard=committed"),
        "stderr: {stderr}"
    );
    assert_cutover_readiness_ready(&stderr);
    assert!(
        stderr.contains("schema cutover complete. SCHEMA_VERSION=2 active"),
        "stderr: {stderr}"
    );
    assert!(
        manifest
            .parent()
            .unwrap()
            .join("POST_V2_MIGRATE_MANIFEST")
            .is_file(),
        "post-migrate manifest must be written next to the backup manifest"
    );

    let pool = Connection::open(&db).expect("reopen db");
    // Schema v2 atomic cutover (ADR 0018): the boundary row is now mirrored
    // into SQLite, so the events count gains exactly the boundary delta.
    // `apply_pending` is idempotent; `_migrations` does not gain rows during
    // the cutover branch.
    assert_eq!(
        table_count(&pool, "events"),
        cortex_store::verify::SCHEMA_V1_TO_V2_EVENT_BOUNDARY_DELTA
    );
    assert_eq!(table_count(&pool, "_migrations"), migrations_before);
    assert!(has_column(&pool, "events", "source_attestation_json"));
    assert!(has_table(&pool, "memory_session_uses"));

    let boundary_report =
        verify_schema_migration_v1_to_v2_boundary(&event_log_path, true).expect("boundary audit");
    assert!(boundary_report.ok(), "boundary report: {boundary_report:?}");
    assert_eq!(boundary_report.boundary_rows.len(), 1);
    let boundary_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("boundary head")
        .to_string();
    assert_ne!(
        boundary_head, previous_v1_head,
        "boundary append must advance JSONL head"
    );
}

#[test]
fn migrate_v2_generated_backup_manifest_cuts_over_to_schema_v2() {
    // Schema v2 atomic cutover (ADR 0018): a manifest emitted by
    // `cortex backup --output` against a pre-v2 store drives migrate v2 to
    // success. The post-migrate SQLite events count gains exactly the
    // boundary delta.
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    assert_eq!(cortex_core::SCHEMA_VERSION, 2);
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    let manifest = generate_backup_manifest(tmp.path());
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 0);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("boundary_audit=ok")
            && stderr.contains("post_migrate_mixed_chain_audit=ok")
            && stderr.contains("post_cutover_audit_dispatch=available")
            && stderr.contains("cutover_authority=ok")
            && stderr.contains("cutover_approved=true")
            && stderr.contains("cutover_guard=committed")
            && stderr.contains("schema cutover complete. SCHEMA_VERSION=2 active"),
        "stderr: {stderr}"
    );
    assert_cutover_readiness_ready(&stderr);
    assert!(
        manifest
            .parent()
            .unwrap()
            .join("POST_V2_MIGRATE_MANIFEST")
            .is_file(),
        "post-migrate manifest must be written next to the backup manifest"
    );

    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(
        table_count(&pool, "events"),
        events_before + cortex_store::verify::SCHEMA_V1_TO_V2_EVENT_BOUNDARY_DELTA
    );
    assert!(has_column(&pool, "events", "source_attestation_json"));
    assert!(has_table(&pool, "memory_session_uses"));
    let boundary_report =
        verify_schema_migration_v1_to_v2_boundary(&event_log_path, true).expect("boundary audit");
    assert!(boundary_report.ok(), "boundary report: {boundary_report:?}");
    assert_eq!(boundary_report.boundary_rows.len(), 1);
}

#[test]
fn migrate_v2_repeated_full_path_cannot_append_second_boundary() {
    // Schema v2 atomic cutover (ADR 0018): the first migrate v2 run cuts over
    // to schema v2 (exit 0). A second migrate v2 run against the now-migrated
    // store finds the boundary already present and refuses to append a
    // duplicate without state mutation (ADR 0033 §1 exactly-once invariant).
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let manifest = generate_backup_manifest(tmp.path());
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);

    let first = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );
    assert_exit(&first, 0);
    let first_stderr = String::from_utf8_lossy(&first.stderr);
    assert!(
        first_stderr.contains("cutover_authority=ok")
            && first_stderr.contains("cutover_approved=true")
            && first_stderr.contains("schema cutover complete"),
        "stderr: {first_stderr}"
    );
    let boundary_report = verify_schema_migration_v1_to_v2_boundary(&event_log_path, true)
        .expect("boundary audit after first run");
    assert!(boundary_report.ok(), "boundary report: {boundary_report:?}");
    assert_eq!(boundary_report.boundary_rows.len(), 1);
    let first_boundary_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("boundary head")
        .to_string();
    let migrations_after_first = {
        let pool = Connection::open(&db).expect("reopen db after first cutover");
        table_count(&pool, "_migrations")
    };

    let second = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );

    // The second run must refuse — the boundary already exists.
    let second_code = second.status.code().expect("second run exit code");
    let second_stderr = String::from_utf8_lossy(&second.stderr);
    assert_ne!(
        second_code, 0,
        "second migrate v2 against already-cut-over store must not succeed: stderr {second_stderr}"
    );
    assert!(
        second_stderr.contains("schema_migration.v1_to_v2 boundary already exists")
            || second_stderr.contains("boundary already exists")
            || second_stderr.contains("boundary preflight"),
        "stderr: {second_stderr}"
    );
    let boundary_report = verify_schema_migration_v1_to_v2_boundary(&event_log_path, true)
        .expect("boundary audit after second run");
    assert!(boundary_report.ok(), "boundary report: {boundary_report:?}");
    assert_eq!(boundary_report.boundary_rows.len(), 1);
    let second_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("boundary head remains")
        .to_string();
    assert_eq!(second_head, first_boundary_head);
    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "_migrations"), migrations_after_first);
    assert_eq!(cortex_core::SCHEMA_VERSION, 2);
}

#[test]
fn audit_verify_rejects_payload_tamper_after_v1_to_v2_boundary_event() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let manifest = generate_backup_manifest(tmp.path());
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);
    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );
    // Schema v2 atomic cutover (ADR 0018): migrate v2 now succeeds.
    assert_exit(&out, 0);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("boundary_audit=ok")
            && stderr.contains("post_migrate_mixed_chain_audit=ok"),
        "stderr: {stderr}"
    );

    tamper_last_jsonl_event_payload(&event_log_path);
    let out = run_in(
        tmp.path(),
        &["audit", "verify", "--require-v1-to-v2-boundary"],
    );

    assert_exit(&out, 3);
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stdout.contains("audit verify:"), "stdout: {stdout}");
    assert!(
        stderr.contains("PayloadHashMismatch") || stderr.contains("EventHashMismatch"),
        "stderr: {stderr}"
    );
}

#[test]
fn audit_verify_accepts_historical_v1_boundary_and_new_v2_rows() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let manifest = generate_backup_manifest(tmp.path());
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);
    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );
    // Schema v2 atomic cutover (ADR 0018): migrate v2 now succeeds, so the
    // post-boundary v2 row is appended on top of a real cutover.
    assert_exit(&out, 0);
    append_post_boundary_schema_v2_event(&event_log_path);

    let out = run_in(
        tmp.path(),
        &["audit", "verify", "--require-v1-to-v2-boundary"],
    );

    assert_exit(&out, 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("audit verify:"), "stdout: {stdout}");
    assert!(stdout.contains("0 failures"), "stdout: {stdout}");
}

#[test]
fn migrate_v2_rejects_malformed_backup_manifest_without_mutation() {
    assert_backup_manifest_rejected_without_mutation(
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1}"#,
        7,
        &[
            "not a valid backup manifest",
            "missing field `sqlite_store`",
        ],
    );
}

#[test]
fn migrate_v2_rejects_invalid_json_backup_manifest_without_mutation() {
    assert_backup_manifest_rejected_without_mutation(
        r#"{"kind":"cortex_pre_v2_backup","schema_version":"#,
        7,
        &["not a valid backup manifest"],
    );
}

#[test]
fn migrate_v2_rejects_wrong_kind_backup_manifest_without_mutation() {
    assert_backup_manifest_rejected_without_mutation(
        r#"{"kind":"generic_backup","schema_version":1,"sqlite_store":"state.sqlite","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z"}"#,
        7,
        &[
            "invalid kind `generic_backup`",
            "expected cortex_pre_v2_backup",
        ],
    );
}

#[test]
fn migrate_v2_rejects_wrong_schema_backup_manifest_without_mutation() {
    assert_backup_manifest_rejected_without_mutation(
        r#"{"kind":"cortex_pre_v2_backup","schema_version":2,"sqlite_store":"state.sqlite","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z"}"#,
        4,
        &["has schema_version 2; expected 1"],
    );
}

#[test]
fn migrate_v2_rejects_empty_backup_manifest_fields_without_mutation() {
    assert_backup_manifest_rejected_without_mutation(
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z"}"#,
        7,
        &["empty `sqlite_store`"],
    );
}

#[test]
fn migrate_v2_rejects_missing_backup_artifacts_without_mutation() {
    assert_backup_manifest_rejected_without_mutation(
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"missing-state.sqlite","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z"}"#,
        7,
        &["missing `sqlite_store` artifact", "missing-state.sqlite"],
    );
}

#[test]
fn migrate_v2_rejects_absolute_backup_artifact_paths_without_mutation() {
    let absolute_artifact = std::env::current_dir()
        .unwrap()
        .join("state.sqlite")
        .to_string_lossy()
        .replace('\\', "\\\\");
    let manifest = format!(
        r#"{{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"{absolute_artifact}","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z"}}"#
    );
    assert_backup_manifest_rejected_without_mutation(
        &manifest,
        7,
        &["absolute paths are not accepted"],
    );
}

#[test]
fn migrate_v2_rejects_parent_traversal_backup_artifact_paths_without_mutation() {
    assert_backup_manifest_rejected_without_mutation(
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"../state.sqlite","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z"}"#,
        7,
        &["parent-directory traversal is not accepted"],
    );
}

#[test]
fn migrate_v2_rejects_missing_backup_jsonl_artifact_without_mutation() {
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    let manifest = tmp.path().join("backup-manifest.json");
    std::fs::write(tmp.path().join("state.sqlite"), "sqlite backup placeholder")
        .expect("write sqlite backup artifact");
    std::fs::write(
        &manifest,
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"state.sqlite","jsonl_mirror":"missing-events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z"}"#,
    )
    .expect("write backup manifest");

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("missing `jsonl_mirror` artifact")
            && stderr.contains("missing-events.jsonl"),
        "stderr: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "events"), events_before);
    // Post-cutover (ADR 0018): `apply_pending` adds the S2.9 expand column as
    // part of the default migration bundle. The manifest rejection still
    // fires before any boundary mutation occurs.
    assert!(has_column(&pool, "events", "source_attestation_json"));
}

#[test]
fn migrate_v2_rejects_invalid_backup_manifest_timestamp_after_artifacts_exist_without_mutation() {
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    let manifest = tmp.path().join("backup-manifest.json");
    std::fs::write(tmp.path().join("state.sqlite"), "sqlite backup placeholder")
        .expect("write sqlite backup artifact");
    std::fs::write(tmp.path().join("events.jsonl"), "jsonl backup placeholder")
        .expect("write jsonl backup artifact");
    std::fs::write(
        &manifest,
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"state.sqlite","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"not-a-date"}"#,
    )
    .expect("write backup manifest");

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("invalid `backup_timestamp`") && stderr.contains("expected RFC3339"),
        "stderr: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "events"), events_before);
    // Post-cutover (ADR 0018): `apply_pending` adds the S2.9 expand column as
    // part of the default migration bundle.
    assert!(has_column(&pool, "events", "source_attestation_json"));
}

#[test]
fn migrate_v2_dry_run_rejects_backup_manifest_flag_without_mutation() {
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    let manifest = tmp.path().join("backup-manifest.json");
    write_valid_backup_manifest(&manifest);

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--dry-run",
            "--backup-manifest",
            manifest.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 2);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--backup-manifest") && stderr.contains("not accepted with --dry-run"),
        "stderr: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "events"), events_before);
    // Post-cutover (ADR 0018): `apply_pending` adds the S2.9 expand column as
    // part of the default migration bundle.
    assert!(has_column(&pool, "events", "source_attestation_json"));
}

/// Punch list #17 acceptance: a CLI invocation without `--operator-attestation`
/// MUST refuse the cutover and leave no JSONL row written. This exercises the
/// composed `Reject` final outcome at the migration authority root (the
/// missing attestation drives `Reject` through the contributor stack).
#[test]
fn migrate_v2_refuses_cutover_without_operator_attestation() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    let previous_v1_head = JsonlLog::open(&event_log_path)
        .expect("open event log")
        .head()
        .expect("v1 head")
        .to_string();
    let manifest = tmp.path().join("backup-manifest.json");
    write_valid_backup_manifest(&manifest);

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--operator-attestation"),
        "stderr should name the new flag: {stderr}"
    );
    assert!(stderr.contains("ADR 0010"), "stderr: {stderr}");
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    // No JSONL row appended; v1 head unchanged.
    let current_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("v1 head still present")
        .to_string();
    assert_eq!(current_head, previous_v1_head);
    // No SQLite events rows added either.
    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "events"), events_before);
}

/// Punch list #17 acceptance: a CLI invocation with an attestation envelope
/// whose declared boundary payload does NOT match the just-computed boundary
/// triple MUST fail closed (Quarantine-class outcome — the attestation cannot
/// be validated against the proposed mutation). Writes nothing.
#[test]
fn migrate_v2_refuses_cutover_when_operator_attestation_targets_wrong_boundary() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    let previous_v1_head = JsonlLog::open(&event_log_path)
        .expect("open event log")
        .head()
        .expect("v1 head")
        .to_string();
    let manifest = tmp.path().join("backup-manifest.json");
    write_valid_backup_manifest(&manifest);

    let (_head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    // Sign an attestation envelope against a fabricated `previous_v1_head_hash`
    // so the verifier refuses the envelope at the boundary-mismatch check.
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(
        &attestation,
        "0000000000000000000000000000000000000000000000000000000000000000",
        &script_digest,
        &fixture_digest,
    );

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("previous_v1_head_hash") && stderr.contains("mismatch"),
        "stderr should name the boundary mismatch: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    // Nothing was written.
    let current_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("v1 head still present")
        .to_string();
    assert_eq!(current_head, previous_v1_head);
    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "events"), events_before);
}

/// Punch list #17 acceptance: a CLI invocation with a forged Ed25519 signature
/// on the attestation envelope MUST fail closed. Writes nothing.
#[test]
fn migrate_v2_refuses_cutover_when_operator_attestation_signature_is_forged() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let previous_v1_head = JsonlLog::open(&event_log_path)
        .expect("open event log")
        .head()
        .expect("v1 head")
        .to_string();
    let manifest = tmp.path().join("backup-manifest.json");
    write_valid_backup_manifest(&manifest);

    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation_path = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation_path, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);
    // Forge the signature: flip every byte of `signature_hex`.
    let raw = std::fs::read_to_string(&attestation_path).expect("read envelope");
    let mut envelope: serde_json::Value = serde_json::from_str(&raw).expect("envelope decodes");
    let sig_hex = envelope["signature_hex"]
        .as_str()
        .expect("signature_hex present")
        .to_string();
    let mut forged = String::with_capacity(sig_hex.len());
    for c in sig_hex.chars() {
        let v = u8::from_str_radix(&c.to_string(), 16).expect("hex");
        forged.push_str(&format!("{:x}", v ^ 0x0f));
    }
    envelope["signature_hex"] = serde_json::Value::String(forged);
    std::fs::write(
        &attestation_path,
        serde_json::to_string_pretty(&envelope).unwrap(),
    )
    .expect("rewrite forged envelope");

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation_path.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("Ed25519 signature did not verify")
            || stderr.contains("signature did not verify"),
        "stderr should surface signature rejection: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    let current_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("v1 head still present")
        .to_string();
    assert_eq!(current_head, previous_v1_head);
}

/// Punch list #17 acceptance: a CLI invocation with a valid operator
/// attestation and `--unattended-migrate` MUST succeed.
#[test]
fn migrate_v2_unattended_migrate_succeeds_when_operator_attestation_is_valid() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let manifest = generate_backup_manifest(tmp.path());
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--unattended-migrate",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 0);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("operator_attestation_verified=true"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("schema cutover complete. SCHEMA_VERSION=2 active"),
        "stderr: {stderr}"
    );

    let boundary_report = verify_schema_migration_v1_to_v2_boundary(&event_log_path, true)
        .expect("boundary audit after cutover");
    assert!(boundary_report.ok());
    assert_eq!(boundary_report.boundary_rows.len(), 1);
}

#[test]
fn migrate_v2_unattended_migrate_refuses_until_operator_attestation_is_supplied() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    let migrations_before = table_count(&pool, "_migrations");
    let previous_v1_head = JsonlLog::open(&event_log_path)
        .expect("open event log")
        .head()
        .expect("v1 head")
        .to_string();
    let manifest = tmp.path().join("backup-manifest.json");
    write_valid_backup_manifest(&manifest);

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--unattended-migrate",
            "--backup-manifest",
            manifest.to_str().unwrap(),
        ],
    );

    // Post Gate 5 punch list #17: `--unattended-migrate` is unblocked when an
    // `--operator-attestation <PATH>` envelope is supplied. Without it the
    // command MUST still refuse with a clearer reason naming the new flag,
    // not the old "not yet wired" message.
    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--unattended-migrate requires --operator-attestation"),
        "stderr should name the new flag requirement: {stderr}"
    );
    assert!(
        stderr.contains("ADR 0010"),
        "stderr should cite ADR 0010 doctrine: {stderr}"
    );
    assert_cutover_readiness_ready(&stderr);
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "events"), events_before);
    assert_eq!(table_count(&pool, "_migrations"), migrations_before);
    // Post-cutover: the default migration bundle creates the S2.9 column even
    // before `--unattended-migrate` is invoked. The unattended refusal still
    // fires before any boundary mutation.
    assert!(has_column(&pool, "events", "source_attestation_json"));
    assert!(has_table(&pool, "memory_session_uses"));
    let current_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("v1 head still present")
        .to_string();
    assert_eq!(current_head, previous_v1_head);
}

#[test]
fn doctor_strict_passes_when_schema_versions_match() {
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");

    let out = run_in(tmp.path(), &["doctor", "--strict"]);

    assert_exit(&out, 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    // Post-cutover (ADR 0018): `SCHEMA_VERSION = 2`.
    assert!(
        stdout.contains("schema_version matches code version 2"),
        "stdout: {stdout}"
    );
}

#[test]
fn doctor_strict_exits_schema_mismatch_and_names_invariant() {
    // Post-cutover (ADR 0018, ADR 0033 §6): `SCHEMA_VERSION = 2`, so a row
    // claiming `schema_version = 3` is a *future* row this binary cannot
    // frame and must fail closed.
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    pool.execute(
        "INSERT INTO events (
            id, schema_version, observed_at, recorded_at, source_json, event_type,
            trace_id, session_id, domain_tags_json, payload_json, payload_hash,
            prev_event_hash, event_hash
        ) VALUES (
            'evt_future', 3, '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z',
            '{\"kind\":\"test\"}', 'test.event', NULL, NULL, '[]', '{}',
            'payload-hash', NULL, 'event-hash'
        );",
        [],
    )
    .expect("insert mismatched event");

    let out = run_in(tmp.path(), &["doctor", "--strict"]);

    assert_exit(&out, 4);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("schema_version.events.matches_code"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("row evt_future has schema_version 3; expected 2"),
        "stderr: {stderr}"
    );
}

#[test]
fn store_open_commands_refuse_future_v3_rows_without_mutation() {
    // Post-cutover (ADR 0018, ADR 0033 §6): `SCHEMA_VERSION = 2`. A row that
    // claims `schema_version = 3` is a future row this binary cannot frame
    // and must fail closed before any side-effect.
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    pool.execute(
        "INSERT INTO events (
            id, schema_version, observed_at, recorded_at, source_json, event_type,
            trace_id, session_id, domain_tags_json, payload_json, payload_hash,
            prev_event_hash, event_hash
        ) VALUES (
            'evt_future_v3', 3, '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z',
            '{\"kind\":\"test\"}', 'test.event', NULL, NULL, '[]', '{}',
            'payload-hash', NULL, 'event-hash'
        );",
        [],
    )
    .expect("insert future v3 event row");
    let events_before = table_count(&pool, "events");
    let traces_before = table_count(&pool, "traces");
    let migrations_before = table_count(&pool, "_migrations");

    let out = run_in(tmp.path(), &["memory", "search", "anything"]);

    assert_exit(&out, 4);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("cortex memory search: schema_version.events.matches_code"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("has schema_version 3; expected 2"),
        "stderr: {stderr}"
    );

    let pool = Connection::open(&db).expect("reopen initialized db");
    assert_eq!(table_count(&pool, "events"), events_before);
    assert_eq!(table_count(&pool, "traces"), traces_before);
    assert_eq!(table_count(&pool, "_migrations"), migrations_before);
}

#[test]
fn doctor_strict_exits_schema_mismatch_for_missing_required_column() {
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    pool.execute("ALTER TABLE events DROP COLUMN payload_hash;", [])
        .expect("drop payload_hash");

    let out = run_in(tmp.path(), &["doctor", "--strict"]);

    assert_exit(&out, 4);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("schema_shape.events.payload_hash.exists"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("table events is missing required column payload_hash"),
        "stderr: {stderr}"
    );
}

#[test]
fn doctor_strict_rejects_duplicate_schema_v2_boundary_rows() {
    let tmp = tempfile::tempdir().unwrap();
    let (_db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());

    let mut log = JsonlLog::open(&event_log_path).expect("open event log");
    let v1_head = log.head().expect("v1 head").to_string();
    let first_boundary = log
        .append_schema_migration_v1_to_v2(
            SchemaMigrationV1ToV2Payload::new(v1_head, "script-digest", None, "fixture-digest"),
            &schema_migration_v1_to_v2_policy_decision_test_allow(),
        )
        .expect("append first boundary");
    log.append_schema_migration_v1_to_v2(
        SchemaMigrationV1ToV2Payload::new(first_boundary, "script-digest", None, "fixture-digest"),
        &schema_migration_v1_to_v2_policy_decision_test_allow(),
    )
    .expect("append duplicate boundary");

    let out = run_in(tmp.path(), &["doctor", "--strict"]);

    assert_exit(&out, 4);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("schema_migration.v1_to_v2.boundary.duplicate"),
        "stderr: {stderr}"
    );
    assert!(stderr.contains("Duplicate"), "stderr: {stderr}");
}

#[test]
fn store_open_commands_refuse_unknown_future_migration() {
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    pool.execute("INSERT INTO _migrations (name) VALUES ('999_future');", [])
        .expect("insert unknown migration");

    let out = run_in(tmp.path(), &["memory", "search", "anything"]);

    assert_exit(&out, 4);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("cortex memory search: schema_migration.known_to_code"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("migration 999_future is unknown to this binary"),
        "stderr: {stderr}"
    );
}

/// R1 (RED_TEAM_FINDINGS phase B): refuse a `cortex_pre_v2_backup` manifest
/// pointed at a live store that already has v2 rows outside the boundary.
///
/// Scenario: a (simulated) fresh-v2 store gets a backup manifest with
/// `kind=cortex_pre_v2_backup` (which is what `cortex backup` would emit
/// today because it decides kind solely by JSONL boundary presence). The
/// CLI must refuse closed with the stable invariant
/// `migrate.v2.backup_manifest.pre_v2_kind_but_v2_rows_present`.
#[test]
fn migrate_v2_refuses_pre_v2_manifest_when_live_store_has_post_v2_rows() {
    let tmp = tempfile::tempdir().unwrap();
    let db = init(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    // Force one v2 events row outside any boundary, simulating a fresh-v2
    // store. The row carries a non-boundary kind so the new helper does
    // not exclude it from the count.
    pool.execute(
        "INSERT INTO events (
            id, schema_version, observed_at, recorded_at, source_json, event_type,
            trace_id, session_id, domain_tags_json, payload_json, payload_hash,
            prev_event_hash, event_hash, source_attestation_json
        ) VALUES (
            'evt_fresh_v2_misuse', 2, '2026-05-04T12:00:00Z',
            '2026-05-04T12:00:01Z', '{\"kind\":\"test\"}', 'tool.result',
            NULL, NULL, '[]', '{\"step\":1}', 'payload-hash', NULL,
            'event-hash-fresh-v2-misuse', '{\"state\":\"missing\",\"value\":null}'
        );",
        [],
    )
    .expect("seed fresh-v2 events row outside the boundary");
    let events_before = table_count(&pool, "events");
    drop(pool);

    let manifest = tmp.path().join("backup-manifest.json");
    write_valid_backup_manifest(&manifest);

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("migrate.v2.backup_manifest.pre_v2_kind_but_v2_rows_present"),
        "stderr should surface the R1 invariant: {stderr}"
    );
    assert!(
        stderr.contains("events_post_v2=1"),
        "stderr should report the fresh-v2 events count: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(
        table_count(&pool, "events"),
        events_before,
        "R1 guard must refuse before any boundary mutation"
    );
}

/// R1 (RED_TEAM_FINDINGS phase B): the guard exempts the boundary row
/// itself — a re-run against an already-cut-over store must trip
/// `boundary_preflight` ("boundary already exists"), not the R1 invariant.
#[test]
fn migrate_v2_r1_guard_exempts_existing_boundary_row() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let manifest = generate_backup_manifest(tmp.path());
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);

    let first = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );
    assert_exit(&first, 0);
    let boundary_report = verify_schema_migration_v1_to_v2_boundary(&event_log_path, true)
        .expect("boundary audit after first run");
    assert!(boundary_report.ok());

    // Second run with the same pre-v2 manifest. The R1 guard must NOT fire
    // — the boundary row is exempt. Instead, `boundary_preflight` refuses
    // with the exactly-once invariant.
    let second = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );
    let second_stderr = String::from_utf8_lossy(&second.stderr);
    assert!(
        !second_stderr.contains("pre_v2_kind_but_v2_rows_present"),
        "R1 guard must not fire on the boundary row itself: {second_stderr}"
    );
    assert!(
        second_stderr.contains("boundary already exists"),
        "second cutover must refuse via boundary_preflight: {second_stderr}"
    );
}

/// B1 (RED_TEAM_FINDINGS phase B): aborting the SQLite cutover transaction
/// mid-flight MUST leave the SQLite store unchanged.
///
/// The trigger is a row-count baseline lie: the backup manifest declares
/// pre-migrate `events = 999`, but the live store has the legitimate
/// post-ingest count. The cutover transaction opens, expand/backfill runs
/// in-tx, the JSONL boundary row is appended (durable, outside the tx),
/// the SQLite mirror INSERTs the boundary row in-tx, and then
/// `verify_post_migrate_row_counts` inside the tx surfaces the drift and
/// returns failures. The transaction is dropped without commit, rolling
/// back every SQLite mutation made during the cutover body. The pre-cutover
/// SQLite snapshot must match byte-for-row.
///
/// Stable rollback signal: `migrate.v2.cutover_tx.rolled_back` in stderr.
#[test]
fn migrate_v2_cutover_tx_rolls_back_sqlite_on_post_mirror_failure() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");

    // Snapshot the pre-cutover SQLite state. The strongest in-tx mutation
    // the cutover body performs after the JSONL append is the SQLite
    // boundary-row INSERT (mirror_single_event_into_sqlite_in_tx). If the
    // surrounding tx rolls back, that INSERT must vanish — the post-attempt
    // events count must equal the pre-attempt events count, and the
    // boundary row's SQLite id must NOT exist in `events`.
    let events_before = table_count(&pool, "events");
    let traces_before = table_count(&pool, "traces");
    let episodes_before = table_count(&pool, "episodes");
    let memories_before = table_count(&pool, "memories");
    let context_packs_before = table_count(&pool, "context_packs");
    let migrations_before = table_count(&pool, "_migrations");
    let previous_v1_head = JsonlLog::open(&event_log_path)
        .expect("open event log")
        .head()
        .expect("v1 head")
        .to_string();
    drop(pool);

    // Backup manifest with deliberately wrong table_row_counts so the
    // in-tx `verify_post_migrate_row_counts` step fails AFTER the JSONL
    // boundary append has fsynced. The expand/backfill stage and the
    // boundary mirror INSERT both run, then the count compare returns a
    // mismatch and the surrounding tx is rolled back.
    let manifest = tmp.path().join("backup-manifest.json");
    std::fs::write(tmp.path().join("state.sqlite"), "sqlite backup placeholder")
        .expect("write sqlite backup artifact");
    std::fs::write(tmp.path().join("events.jsonl"), "jsonl backup placeholder")
        .expect("write jsonl backup artifact");
    std::fs::write(
        &manifest,
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"state.sqlite","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z","table_row_counts":{"events":999,"traces":0,"episodes":0,"memories":0}}"#,
    )
    .expect("write tampered backup manifest");

    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );

    let code = out.status.code().expect("process exited via signal");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_ne!(
        code, 0,
        "cutover with wrong baseline must not succeed; stderr: {stderr}"
    );
    assert!(
        stderr.contains("schema_v2_post_migrate.row_count"),
        "stderr should surface a count-mismatch invariant: {stderr}"
    );
    assert!(
        stderr.contains("migrate.v2.cutover_tx.rolled_back"),
        "stderr should surface the SQLite-side rollback invariant: {stderr}"
    );

    // SQLite-side state must be identical to before the cutover attempt:
    // expand/backfill rolled back; boundary mirror INSERT rolled back;
    // re-backfill rolled back. The JSONL boundary append is durable by
    // doctrine — the cutover-tx fix does NOT roll back JSONL.
    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(
        table_count(&pool, "events"),
        events_before,
        "events count must be unchanged: boundary mirror INSERT rolled back"
    );
    assert_eq!(table_count(&pool, "traces"), traces_before);
    assert_eq!(table_count(&pool, "episodes"), episodes_before);
    assert_eq!(table_count(&pool, "memories"), memories_before);
    assert_eq!(table_count(&pool, "context_packs"), context_packs_before);
    assert_eq!(table_count(&pool, "_migrations"), migrations_before);
    // Boundary row must NOT exist in SQLite: read the boundary's event_hash
    // from the durable JSONL row and assert no SQLite row carries it.
    let durable_boundary_hash = JsonlLog::open(&event_log_path)
        .expect("reopen event log for boundary hash")
        .head()
        .expect("durable boundary head")
        .to_string();
    let boundary_row_in_sqlite: u64 = pool
        .query_row(
            "SELECT COUNT(*) FROM events WHERE event_hash = ?1;",
            [&durable_boundary_hash],
            |row| row.get(0),
        )
        .expect("count boundary row in SQLite");
    assert_eq!(
        boundary_row_in_sqlite, 0,
        "boundary mirror INSERT must roll back: SQLite still carries the row at event_hash={durable_boundary_hash}"
    );

    // JSONL boundary append stayed durable (BUILD_SPEC §7 + ADR 0033 §1):
    // the canonical record advances even when the SQLite mirror tx rolls
    // back. A second migrate v2 run hitting this store finds the boundary
    // already present and refuses (boundary_preflight); recovery is the
    // documented "JSONL-ahead-of-SQLite" path in the commit body.
    let post_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log after rollback")
        .head()
        .expect("post-attempt head")
        .to_string();
    assert_ne!(
        post_head, previous_v1_head,
        "JSONL boundary append must remain durable across SQLite-side rollback"
    );
    let boundary_report =
        verify_schema_migration_v1_to_v2_boundary(&event_log_path, true).expect("boundary audit");
    assert!(boundary_report.ok(), "boundary report: {boundary_report:?}");
    assert_eq!(boundary_report.boundary_rows.len(), 1);

    // Second migrate attempt refuses on the durable JSONL boundary. This
    // documents the recovery surface: today operators must restore from
    // blessed backup; a `--resume-mirror` flag is TODO.
    let second = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );
    let second_stderr = String::from_utf8_lossy(&second.stderr);
    assert!(
        second_stderr.contains("boundary already exists"),
        "second cutover must refuse on durable JSONL boundary: {second_stderr}"
    );
}

/// B1 follow-up (RED_TEAM_FINDINGS phase B): `cortex migrate v2 --resume-mirror`
/// recovers from the partial-mutation state where the JSONL boundary append
/// succeeded but the SQLite mirror tx rolled back on a later in-tx step.
///
/// Setup mirrors `migrate_v2_cutover_tx_rolls_back_sqlite_on_post_mirror_failure`:
/// a backup manifest with a lie in `table_row_counts.events` causes the in-tx
/// post-migrate count compare to fail, rolling back every SQLite-side mutation
/// while leaving the JSONL boundary durable. With the JSONL-ahead-of-SQLite
/// state established, `--resume-mirror` must:
///   1. Re-mirror the JSONL boundary into SQLite.
///   2. Re-run the legacy-attestation backfill on the boundary row.
///   3. Pass the default-v2 cutover readiness gate.
///   4. Commit the recovery transaction and emit
///      `migrate.v2.resume_mirror.completed`.
#[test]
fn migrate_v2_resume_mirror_recovers_after_cutover_tx_rollback() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    drop(pool);

    // Drive the cutover tx into rollback via a tampered row-count baseline,
    // mirroring the B1 rollback test above. After this run:
    //   - JSONL carries exactly one boundary row (durable).
    //   - SQLite has the pre-cutover snapshot back, with no boundary row.
    let manifest = tmp.path().join("backup-manifest.json");
    std::fs::write(tmp.path().join("state.sqlite"), "sqlite backup placeholder")
        .expect("write sqlite backup artifact");
    std::fs::write(tmp.path().join("events.jsonl"), "jsonl backup placeholder")
        .expect("write jsonl backup artifact");
    std::fs::write(
        &manifest,
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"state.sqlite","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z","table_row_counts":{"events":999,"traces":0,"episodes":0,"memories":0}}"#,
    )
    .expect("write tampered backup manifest");
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);
    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );
    let code = out.status.code().expect("first run exit code");
    let stderr_first = String::from_utf8_lossy(&out.stderr);
    assert_ne!(code, 0, "tampered cutover must not succeed: {stderr_first}");
    assert!(
        stderr_first.contains("migrate.v2.cutover_tx.rolled_back"),
        "first run must trigger the cutover-tx rollback: {stderr_first}"
    );

    // Confirm the JSONL-ahead-of-SQLite state holds before invoking resume.
    let durable_boundary_hash = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("durable boundary head")
        .to_string();
    let pool = Connection::open(&db).expect("reopen db");
    let boundary_row_in_sqlite_pre_resume: u64 = pool
        .query_row(
            "SELECT COUNT(*) FROM events WHERE event_hash = ?1;",
            [&durable_boundary_hash],
            |row| row.get(0),
        )
        .expect("count boundary row in SQLite before resume");
    assert_eq!(
        boundary_row_in_sqlite_pre_resume, 0,
        "preconditions for resume: boundary must be in JSONL but not SQLite"
    );
    assert_eq!(table_count(&pool, "events"), events_before);
    drop(pool);

    // Run the recovery surface.
    let resume = run_in(tmp.path(), &["migrate", "v2", "--resume-mirror"]);
    assert_exit(&resume, 0);
    let resume_stderr = String::from_utf8_lossy(&resume.stderr);
    assert!(
        resume_stderr.contains("migrate.v2.resume_mirror.completed"),
        "resume must surface the completion invariant: {resume_stderr}"
    );
    assert!(
        resume_stderr.contains(&durable_boundary_hash),
        "resume must report the boundary event hash it mirrored: {resume_stderr}"
    );

    // SQLite now carries the boundary row (events count = pre + boundary
    // delta) and the boundary row's source_attestation_json is populated
    // by the in-tx re-backfill, so the readiness gate is green.
    let pool = Connection::open(&db).expect("reopen db after resume");
    assert_eq!(
        table_count(&pool, "events"),
        events_before + cortex_store::verify::SCHEMA_V1_TO_V2_EVENT_BOUNDARY_DELTA,
        "boundary mirror INSERT must be durable after --resume-mirror commits"
    );
    let boundary_row_in_sqlite_post_resume: u64 = pool
        .query_row(
            "SELECT COUNT(*) FROM events WHERE event_hash = ?1;",
            [&durable_boundary_hash],
            |row| row.get(0),
        )
        .expect("count boundary row in SQLite after resume");
    assert_eq!(boundary_row_in_sqlite_post_resume, 1);
    let boundary_attestation_set: u64 = pool
        .query_row(
            "SELECT COUNT(*) FROM events \
             WHERE event_hash = ?1 AND source_attestation_json IS NOT NULL;",
            [&durable_boundary_hash],
            |row| row.get(0),
        )
        .expect("verify boundary source_attestation_json populated");
    assert_eq!(
        boundary_attestation_set, 1,
        "legacy-attestation backfill must stamp the just-mirrored boundary row"
    );

    // The readiness gate is exercised inside the resume tx; an independent
    // run of `cortex doctor --strict` should still pass on the recovered store.
    let doctor = run_in(tmp.path(), &["doctor", "--strict"]);
    assert_exit(&doctor, 0);
}

/// BUG_HUNT_2026-05-12 BH-4 reproducer (CLI surface).
///
/// The cutover transaction (`run_v2_cutover_tx`) runs
/// `apply_expand_backfill_skeleton` inside its tx. On a store where the
/// schema-v2 expand DDL has not yet been recorded in `_migrations`, the
/// skeleton issues `ALTER TABLE events ADD COLUMN source_attestation_json ...`
/// (plus the side tables `memory_session_uses` and `outcome_memory_relations`)
/// inside the tx. The JSONL boundary append happens OUTSIDE the SQLite tx by
/// doctrine: if any later in-tx step refuses, the SQLite rollback discards
/// every mutation in the tx — including the ALTERs — while the JSONL
/// boundary stays durable.
///
/// Pre-fix `run_v2_resume_mirror` assumed the schema skeleton was durable
/// from the cutover tx and went straight to `mirror_single_event_into_sqlite_in_tx`
/// followed by `backfill_legacy_event_attestations`. On a rolled-back store
/// the latter executes `UPDATE events SET source_attestation_json = ...` and
/// fails closed with a raw SQLite "no such column" error — the recovery
/// surface was unreachable in exactly the scenario it was designed for.
///
/// This test exercises the CLI surface against the same rolled-back-DDL
/// shape the bug-hunt describes: drop the v2 side tables created by the
/// expand skeleton, then invoke `--resume-mirror`. In this codebase
/// `verify_schema_version` (called by `open_default_store` before
/// `run_v2_resume_mirror` runs) ALSO refuses on missing side tables, so the
/// CLI exit is `Exit::SchemaMismatch` (code 4) — strictly better than the
/// raw "no such column" error the bug-hunt describes. The
/// `run_v2_resume_mirror` fix is itself defensive against future divergence
/// between `apply_pending`/`verify_schema_version` and the cutover tx; the
/// idempotency guarantee of the schema-skeleton replay is verified directly
/// in
/// `migrate_v2_resume_mirror_schema_skeleton_replay_is_noop_when_schema_present`.
#[test]
fn migrate_v2_resume_mirror_recovers_from_rolled_back_cutover_with_missing_schema_skeleton() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());

    // Drive the cutover tx into rollback via a tampered row-count baseline so
    // SQLite is rolled back to the pre-cutover snapshot (no boundary row) but
    // JSONL retains the durable boundary append. This is the same B1 partial-
    // mutation shape as the existing resume-mirror reproducer above.
    let manifest = tmp.path().join("backup-manifest.json");
    std::fs::write(tmp.path().join("state.sqlite"), "sqlite backup placeholder")
        .expect("write sqlite backup artifact");
    std::fs::write(tmp.path().join("events.jsonl"), "jsonl backup placeholder")
        .expect("write jsonl backup artifact");
    std::fs::write(
        &manifest,
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"state.sqlite","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z","table_row_counts":{"events":999,"traces":0,"episodes":0,"memories":0}}"#,
    )
    .expect("write tampered backup manifest");
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);
    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );
    let code = out.status.code().expect("first run exit code");
    let stderr_first = String::from_utf8_lossy(&out.stderr);
    assert_ne!(code, 0, "tampered cutover must not succeed: {stderr_first}");
    assert!(
        stderr_first.contains("migrate.v2.cutover_tx.rolled_back"),
        "first run must trigger the cutover-tx rollback: {stderr_first}"
    );

    let durable_boundary_hash = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("durable boundary head")
        .to_string();

    // Surgically drop the v2 side tables `apply_expand_backfill_skeleton`
    // creates to model a rolled-back-DDL surface.
    let pool = Connection::open(&db).expect("reopen db after cutover-tx rollback");
    pool.execute_batch(
        "DROP TABLE IF EXISTS memory_session_uses;
         DROP TABLE IF EXISTS outcome_memory_relations;",
    )
    .expect("drop v2 side tables to model partial DDL rollback");
    drop(pool);

    // Pre-resume preconditions: side tables are gone, boundary row is in
    // JSONL but not in SQLite.
    let pool = Connection::open(&db).expect("reopen db pre-resume");
    assert!(
        !has_table(&pool, "memory_session_uses"),
        "rolled-back DDL must not carry memory_session_uses"
    );
    assert!(
        !has_table(&pool, "outcome_memory_relations"),
        "rolled-back DDL must not carry outcome_memory_relations"
    );
    let boundary_row_in_sqlite_pre_resume: u64 = pool
        .query_row(
            "SELECT COUNT(*) FROM events WHERE event_hash = ?1;",
            [&durable_boundary_hash],
            |row| row.get(0),
        )
        .expect("count boundary row in SQLite pre-resume");
    assert_eq!(
        boundary_row_in_sqlite_pre_resume, 0,
        "preconditions: boundary must be in JSONL but not SQLite"
    );
    drop(pool);

    // `verify_schema_version` is a fail-closed gate on the open-store path.
    // The resume CLI exit must be SchemaMismatch (code 4) with a typed
    // operator-facing diagnostic — strictly better than the raw "no such
    // column" SQLite error the bug-hunt describes. The runbook recovery for
    // this shape is the catastrophic ADR 0033 §3 restore-from-blessed-backup
    // path; the resume-mirror surface is for the more common
    // schema-still-present partial-mutation shape (exercised by the
    // adjacent
    // `migrate_v2_resume_mirror_recovers_after_cutover_tx_rollback` test).
    let resume = run_in(tmp.path(), &["migrate", "v2", "--resume-mirror"]);
    assert_exit(&resume, 4);
    let resume_stderr = String::from_utf8_lossy(&resume.stderr);
    assert!(
        resume_stderr.contains("schema_shape.memory_session_uses.exists")
            || resume_stderr.contains("schema_shape.outcome_memory_relations.exists"),
        "verify_schema_version must surface a typed missing-table diagnostic: {resume_stderr}"
    );
    assert!(
        resume_stderr.contains("resume refused"),
        "resume must report a typed refusal rather than a raw SQLite error: {resume_stderr}"
    );

    // No mutation: JSONL boundary still durable, SQLite still without the
    // boundary row, side tables still absent.
    let pool = Connection::open(&db).expect("reopen db after refused resume");
    assert!(!has_table(&pool, "memory_session_uses"));
    let boundary_row_in_sqlite_post_resume: u64 = pool
        .query_row(
            "SELECT COUNT(*) FROM events WHERE event_hash = ?1;",
            [&durable_boundary_hash],
            |row| row.get(0),
        )
        .expect("count boundary row in SQLite post-resume");
    assert_eq!(
        boundary_row_in_sqlite_post_resume, 0,
        "refused resume must not mutate SQLite"
    );
}

/// BUG_HUNT_2026-05-12 BH-4 idempotency complement: when `--resume-mirror`
/// runs against a store whose schema skeleton IS already present (the common
/// case where the cutover persisted the DDL via `apply_pending` or a prior
/// resume, but the mirror failed downstream and was rolled back), the schema
/// skeleton replay MUST be a structural no-op and MUST NOT surface the
/// `schema_skeleton_replayed` warn token. The recovery still completes.
#[test]
fn migrate_v2_resume_mirror_schema_skeleton_replay_is_noop_when_schema_present() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    drop(pool);

    // Drive the cutover tx into rollback via a tampered row-count baseline.
    // After this run JSONL carries the boundary row; SQLite was rolled back
    // to the pre-cutover snapshot. But because `apply_pending` ran first and
    // bundles `003_schema_v2_expand`, the column survives the rollback (the
    // ALTER happened in a prior, already-committed tx). So the rollback only
    // discarded the mirror INSERT / re-backfill / readiness-gate updates;
    // the schema skeleton is durable.
    let manifest = tmp.path().join("backup-manifest.json");
    std::fs::write(tmp.path().join("state.sqlite"), "sqlite backup placeholder")
        .expect("write sqlite backup artifact");
    std::fs::write(tmp.path().join("events.jsonl"), "jsonl backup placeholder")
        .expect("write jsonl backup artifact");
    std::fs::write(
        &manifest,
        r#"{"kind":"cortex_pre_v2_backup","schema_version":1,"sqlite_store":"state.sqlite","jsonl_mirror":"events.jsonl","tool_version":"cortex-test","backup_timestamp":"2026-05-04T22:00:00Z","table_row_counts":{"events":999,"traces":0,"episodes":0,"memories":0}}"#,
    )
    .expect("write tampered backup manifest");
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);
    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );
    let code = out.status.code().expect("first run exit code");
    let stderr_first = String::from_utf8_lossy(&out.stderr);
    assert_ne!(code, 0, "tampered cutover must not succeed: {stderr_first}");
    assert!(
        stderr_first.contains("migrate.v2.cutover_tx.rolled_back"),
        "first run must trigger the cutover-tx rollback: {stderr_first}"
    );

    // Schema-present preconditions: column survived rollback.
    let pool = Connection::open(&db).expect("reopen db");
    assert!(
        has_column(&pool, "events", "source_attestation_json"),
        "schema-already-present test requires the column on disk"
    );
    drop(pool);

    let durable_boundary_hash = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("durable boundary head")
        .to_string();

    let resume = run_in(tmp.path(), &["migrate", "v2", "--resume-mirror"]);
    assert_exit(&resume, 0);
    let resume_stderr = String::from_utf8_lossy(&resume.stderr);
    assert!(
        resume_stderr.contains("migrate.v2.resume_mirror.completed"),
        "schema-present resume must surface completion: {resume_stderr}"
    );
    // The warn-level replay token MUST NOT fire when nothing was added.
    assert!(
        !resume_stderr.contains("migrate.v2.resume_mirror.schema_skeleton_replayed"),
        "schema-present resume must not surface the schema-skeleton replay token: {resume_stderr}"
    );

    // The recovered store carries the boundary row.
    let pool = Connection::open(&db).expect("reopen db after schema-present resume");
    let boundary_row_in_sqlite_post_resume: u64 = pool
        .query_row(
            "SELECT COUNT(*) FROM events WHERE event_hash = ?1;",
            [&durable_boundary_hash],
            |row| row.get(0),
        )
        .expect("count boundary row in SQLite post-resume");
    assert_eq!(boundary_row_in_sqlite_post_resume, 1);
}

/// B1 follow-up: invoking `--resume-mirror` against a fully-migrated store
/// MUST be a no-op (idempotency). The boundary is already mirrored, so the
/// recovery target is already reached.
#[test]
fn migrate_v2_resume_mirror_is_idempotent_when_boundary_already_mirrored() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());

    // Drive a clean cutover to completion so JSONL and SQLite both carry
    // the boundary row.
    let manifest = generate_backup_manifest(tmp.path());
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    seed_migrate_operator_authority(&db);
    let cutover = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );
    assert_exit(&cutover, 0);
    let boundary_hash = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("boundary head")
        .to_string();
    let pool = Connection::open(&db).expect("reopen db after cutover");
    let events_after_cutover = table_count(&pool, "events");
    drop(pool);

    let resume = run_in(tmp.path(), &["migrate", "v2", "--resume-mirror"]);
    assert_exit(&resume, 0);
    let resume_stderr = String::from_utf8_lossy(&resume.stderr);
    assert!(
        resume_stderr.contains("migrate.v2.resume_mirror.boundary_already_mirrored"),
        "idempotent resume must surface the already-mirrored invariant: {resume_stderr}"
    );
    assert!(
        resume_stderr.contains(&boundary_hash),
        "idempotent resume must name the boundary hash already present: {resume_stderr}"
    );
    assert!(
        !resume_stderr.contains("migrate.v2.resume_mirror.completed"),
        "idempotent resume must NOT emit the completion invariant: {resume_stderr}"
    );

    // No mutation: events count unchanged, JSONL head unchanged.
    let pool = Connection::open(&db).expect("reopen db after idempotent resume");
    assert_eq!(table_count(&pool, "events"), events_after_cutover);
    let post_resume_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log after idempotent resume")
        .head()
        .expect("boundary head still present")
        .to_string();
    assert_eq!(post_resume_head, boundary_hash);
}

/// B1 follow-up: `--resume-mirror` against a pre-cutover store (JSONL has no
/// boundary, SQLite has no boundary) MUST refuse closed. The recovery surface
/// is for the partial-mutation state only; if no cutover has run, the
/// operator should run `cortex migrate v2 --backup-manifest ...` instead.
#[test]
fn migrate_v2_resume_mirror_refuses_when_jsonl_has_no_boundary() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");
    let migrations_before = table_count(&pool, "_migrations");
    drop(pool);
    let head_before = JsonlLog::open(&event_log_path)
        .expect("open event log")
        .head()
        .expect("v1 head")
        .to_string();

    let resume = run_in(tmp.path(), &["migrate", "v2", "--resume-mirror"]);
    assert_exit(&resume, 7);
    let resume_stderr = String::from_utf8_lossy(&resume.stderr);
    assert!(
        resume_stderr.contains("migrate.v2.resume_mirror.no_jsonl_boundary"),
        "wrong-surface resume must surface the no-boundary invariant: {resume_stderr}"
    );
    assert!(
        resume_stderr.contains("no state was changed"),
        "wrong-surface resume must report no-state-changed: {resume_stderr}"
    );

    // No mutation: events count, migrations count, and JSONL head all
    // unchanged.
    let pool = Connection::open(&db).expect("reopen db after refused resume");
    assert_eq!(table_count(&pool, "events"), events_before);
    assert_eq!(table_count(&pool, "_migrations"), migrations_before);
    let head_after = JsonlLog::open(&event_log_path)
        .expect("reopen event log after refused resume")
        .head()
        .expect("v1 head unchanged")
        .to_string();
    assert_eq!(head_after, head_before);
}

/// B1 follow-up: `--resume-mirror` is mutually exclusive with the cutover
/// surfaces (`--dry-run`, `--backup-manifest`, `--unattended-migrate`,
/// `--operator-attestation`). Combining them is a usage error.
#[test]
fn migrate_v2_resume_mirror_is_mutually_exclusive_with_cutover_flags() {
    let tmp = tempfile::tempdir().unwrap();
    init(tmp.path());

    // --resume-mirror + --dry-run.
    let out = run_in(
        tmp.path(),
        &["migrate", "v2", "--resume-mirror", "--dry-run"],
    );
    assert_exit(&out, 2);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--resume-mirror is a partial-mutation recovery surface"),
        "mutual-exclusion refusal must name the recovery-surface contract: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    // --resume-mirror + --backup-manifest.
    let manifest = tmp.path().join("backup-manifest.json");
    write_valid_backup_manifest(&manifest);
    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--resume-mirror",
            "--backup-manifest",
            manifest.to_str().unwrap(),
        ],
    );
    assert_exit(&out, 2);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--resume-mirror is a partial-mutation recovery surface"),
        "stderr: {stderr}"
    );

    // --resume-mirror + --unattended-migrate.
    let out = run_in(
        tmp.path(),
        &["migrate", "v2", "--resume-mirror", "--unattended-migrate"],
    );
    assert_exit(&out, 2);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--resume-mirror is a partial-mutation recovery surface"),
        "stderr: {stderr}"
    );
}

// =============================================================================
// Phase 2.6 — migrate v2 operator temporal authority refusal tests
//
// `docs/design/PHASE_2_6_temporal_authority_revalidation_audit.md` §T1:
// the schema-v1-to-v2 boundary append MUST consult the durable
// `authority_key_timeline` for the operator-supplied key before letting
// the cutover proceed. Pre-closure the contributor was a literal `Allow`;
// post-closure a revoked-after-signing or absent key votes `Reject` and
// the cutover refuses with `migrate.v2.operator_temporal_authority.revalidation_failed`.
// =============================================================================

#[test]
fn migrate_v2_refuses_cutover_when_operator_key_revoked_in_timeline() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    assert_eq!(cortex_core::SCHEMA_VERSION, 2);
    let previous_v1_head = JsonlLog::open(&event_log_path)
        .expect("open event log")
        .head()
        .expect("v1 head")
        .to_string();
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");

    let manifest = tmp.path().join("backup-manifest.json");
    write_valid_backup_manifest(&manifest);
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);

    // Seed the operator-key timeline at `Operator` tier and then revoke
    // the key one second later. The migrate v2 cutover signs `signed_at =
    // Utc::now()` and revalidation should report `RevokedAfterSigning` /
    // `SignedAfterRevocation` -> `Reject`.
    seed_migrate_operator_authority(&db);
    revoke_migrate_operator_authority(&db, Utc.with_ymd_and_hms(2026, 1, 1, 12, 0, 2).unwrap());

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("migrate.v2.operator_temporal_authority.revalidation_failed"),
        "stderr must carry the stable invariant: {stderr}"
    );
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");

    // Nothing was written.
    let current_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("v1 head still present")
        .to_string();
    assert_eq!(current_head, previous_v1_head);
    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "events"), events_before);
}

#[test]
fn migrate_v2_refuses_cutover_when_operator_key_absent_from_timeline() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, event_log_path) = init_layout(tmp.path());
    ingest_minimal_session(tmp.path());
    assert_eq!(cortex_core::SCHEMA_VERSION, 2);
    let previous_v1_head = JsonlLog::open(&event_log_path)
        .expect("open event log")
        .head()
        .expect("v1 head")
        .to_string();
    let pool = Connection::open(&db).expect("open initialized db");
    apply_pending(&pool).expect("apply migrations");
    let events_before = table_count(&pool, "events");

    let manifest = tmp.path().join("backup-manifest.json");
    write_valid_backup_manifest(&manifest);
    let (head, script_digest, fixture_digest) = dry_run_boundary_preflight(tmp.path());
    let attestation = tmp.path().join("operator-attestation.json");
    write_valid_operator_attestation(&attestation, &head, &script_digest, &fixture_digest);
    // Deliberately skip the seed: no `fixture-operator-key` row exists
    // in `authority_key_timeline`. Revalidation must return
    // `KeyUnknown` / `PrincipalUnknown` -> `Reject`.

    let out = run_in(
        tmp.path(),
        &[
            "migrate",
            "v2",
            "--backup-manifest",
            manifest.to_str().unwrap(),
            "--operator-attestation",
            attestation.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("migrate.v2.operator_temporal_authority.revalidation_failed")
            && stderr.contains("key_unknown"),
        "stderr must carry the stable invariant + key_unknown reason: {stderr}"
    );

    // Nothing was written.
    let current_head = JsonlLog::open(&event_log_path)
        .expect("reopen event log")
        .head()
        .expect("v1 head still present")
        .to_string();
    assert_eq!(current_head, previous_v1_head);
    let pool = Connection::open(&db).expect("reopen db");
    assert_eq!(table_count(&pool, "events"), events_before);
}