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
//! CLI tests for restore validation surfaces.

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

use chrono::{TimeZone, Utc};
use cortex_core::{
    Attestor, Event, EventId, EventSource, EventType, InMemoryAttestor, KeyLifecycleState,
    TrustTier, SCHEMA_VERSION,
};
use cortex_ledger::{append_policy_decision_test_allow, current_anchor, JsonlLog};
use cortex_store::repo::{AuthorityRepo, KeyTimelineRecord, PrincipalTimelineRecord};
use rusqlite::Connection;
use serde_json::json;

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

fn run(args: &[&str]) -> std::process::Output {
    let tmp = tempfile::tempdir().expect("isolated cli tempdir");
    run_in(tmp.path(), args)
}

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),
    );
}

fn write_json(path: &Path, value: serde_json::Value) {
    fs::write(path, serde_json::to_vec_pretty(&value).unwrap()).unwrap();
}

fn blake3_digest(bytes: &[u8]) -> String {
    format!("blake3:{}", blake3::hash(bytes).to_hex())
}

fn write_pre_v2_backup(bundle: &Path) -> PathBuf {
    fs::create_dir_all(bundle).unwrap();
    let sqlite = b"sqlite-backup-bytes";
    let jsonl = b"{\"event\":\"backup\"}\n";
    fs::write(bundle.join("cortex.db"), sqlite).unwrap();
    fs::write(bundle.join("events.jsonl"), jsonl).unwrap();
    let manifest = json!({
        "kind": "cortex_pre_v2_backup",
        "schema_version": 1,
        "sqlite_store": "cortex.db",
        "jsonl_mirror": "events.jsonl",
        "tool_version": "cortex-test",
        "backup_timestamp": "2026-05-04T22:00:00Z",
        "sqlite_store_size_bytes": sqlite.len(),
        "sqlite_store_blake3": blake3_digest(sqlite),
        "jsonl_mirror_size_bytes": jsonl.len(),
        "jsonl_mirror_blake3": blake3_digest(jsonl),
    });
    let manifest_path = bundle.join("BACKUP_MANIFEST");
    write_json(&manifest_path, manifest);
    manifest_path
}

fn fixture_event(seq: u64) -> Event {
    Event {
        id: EventId::new(),
        schema_version: SCHEMA_VERSION,
        observed_at: Utc::now(),
        recorded_at: Utc::now(),
        source: EventSource::User,
        event_type: EventType::UserMessage,
        trace_id: None,
        session_id: None,
        domain_tags: vec![],
        payload: json!({ "seq": seq }),
        payload_hash: String::new(),
        prev_event_hash: None,
        event_hash: String::new(),
    }
}

fn append_fixture_event(log_path: &Path) {
    let mut log = JsonlLog::open(log_path).expect("open backup JSONL log");
    log.append(fixture_event(1), &append_policy_decision_test_allow())
        .expect("append backup JSONL event");
}

fn write_manifest_for_artifacts(
    bundle: &Path,
    sqlite_source: &Path,
    jsonl_source: &Path,
) -> PathBuf {
    fs::create_dir_all(bundle).unwrap();
    let sqlite = fs::read(sqlite_source).unwrap();
    let jsonl = fs::read(jsonl_source).unwrap();
    fs::write(bundle.join("cortex.db"), &sqlite).unwrap();
    fs::write(bundle.join("events.jsonl"), &jsonl).unwrap();
    let manifest = json!({
        "kind": "cortex_pre_v2_backup",
        "schema_version": 1,
        "sqlite_store": "cortex.db",
        "jsonl_mirror": "events.jsonl",
        "tool_version": "cortex-test",
        "backup_timestamp": "2026-05-04T22:00:00Z",
        "sqlite_store_size_bytes": sqlite.len(),
        "sqlite_store_blake3": blake3_digest(&sqlite),
        "jsonl_mirror_size_bytes": jsonl.len(),
        "jsonl_mirror_blake3": blake3_digest(&jsonl),
    });
    let manifest_path = bundle.join("BACKUP_MANIFEST");
    write_json(&manifest_path, manifest);
    manifest_path
}

fn read_active_artifacts(db: &Path) -> (Vec<u8>, Vec<u8>) {
    let jsonl = db.parent().unwrap().join("events.jsonl");
    (fs::read(db).unwrap(), fs::read(jsonl).unwrap())
}

fn apply_recovery_dir(db: &Path) -> PathBuf {
    db.parent().unwrap().join(".restore-apply-recovery")
}

fn audit_count(db: &Path, operation: &str) -> i64 {
    let pool = Connection::open(db).expect("open sqlite db for audit count");
    pool.query_row(
        "SELECT COUNT(*) FROM audit_records WHERE operation = ?1;",
        [operation],
        |row| row.get(0),
    )
    .unwrap()
}

fn audit_source_refs(db: &Path, operation: &str) -> serde_json::Value {
    let pool = Connection::open(db).expect("open sqlite db for audit source refs");
    let raw: String = pool
        .query_row(
            "SELECT source_refs_json FROM audit_records WHERE operation = ?1 ORDER BY created_at DESC LIMIT 1;",
            [operation],
            |row| row.get(0),
        )
        .unwrap();
    serde_json::from_str(&raw).expect("audit source_refs_json parses")
}

fn audit_hashes(db: &Path, operation: &str) -> (Option<String>, String) {
    let pool = Connection::open(db).expect("open sqlite db for audit hashes");
    pool.query_row(
        "SELECT before_hash, after_hash FROM audit_records WHERE operation = ?1 ORDER BY created_at DESC LIMIT 1;",
        [operation],
        |row| Ok((row.get(0)?, row.get(1)?)),
    )
    .unwrap()
}

fn init_store(cwd: &Path) -> PathBuf {
    let init = run_in(cwd, &["init"]);
    assert_exit(&init, 0);
    String::from_utf8_lossy(&init.stdout)
        .lines()
        .find(|line| line.starts_with("cortex init: db"))
        .and_then(|line| {
            line.split_once('=')
                .and_then(|(_, rest)| rest.trim().split_once(" ("))
                .map(|(path, _)| PathBuf::from(path))
        })
        .expect("init stdout includes db path")
}

fn apply_store_migrations(db: &Path) -> Connection {
    let pool = Connection::open(db).expect("open initialized store");
    cortex_store::migrate::apply_pending(&pool).expect("apply migrations");
    pool
}

/// Phase 2.6 test helper: write a 32-byte Ed25519 seed file the CLI can
/// consume as `--attestation` / `--operator-verification-key`, and seed
/// the operator-key timeline so that
/// `AuthorityRepo::revalidate(key_id, now)` returns `valid_now = true`
/// for the `Operator` tier. Mirrors `cli_phase2::seed_operator_authority`.
fn restore_attestation_key_fixture(dir: &Path) -> (PathBuf, InMemoryAttestor) {
    let path = dir.join("restore-operator-attestation-key.bin");
    let seed = [0x11u8; 32];
    fs::write(&path, seed).expect("write attestation key fixture");
    let attestor = InMemoryAttestor::from_seed(&seed);
    (path, attestor)
}

/// Seed the operator key + principal timeline rows so that
/// `AuthorityRepo::revalidate` returns `valid_now = true` for the
/// `Operator` tier. Production restore + recover-apply require this
/// before they will pass the temporal-authority gate (Phase 2.6).
fn seed_operator_authority_for_restore(db: &Path, attestor: &InMemoryAttestor) {
    let pool = Connection::open(db).expect("open initialized sqlite db");
    cortex_store::migrate::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: attestor.key_id().to_string(),
            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 operator's signing key effective at `effective_at`.
/// Mirrors `cli_phase2::revoke_operator_authority`. Used by the
/// Phase 2.6 closure refusal tests to assert that a revoked key
/// fails the durable timeline revalidation gate.
fn revoke_operator_authority_for_restore(
    db: &Path,
    attestor: &InMemoryAttestor,
    effective_at: chrono::DateTime<Utc>,
) {
    let pool = Connection::open(db).expect("open initialized sqlite db");
    cortex_store::migrate::apply_pending(&pool).expect("apply migrations");
    AuthorityRepo::new(&pool)
        .append_key_state(
            &KeyTimelineRecord {
                key_id: attestor.key_id().to_string(),
                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 insert_active_memory(pool: &Connection, id: &str, claim: &str, score: f64) {
    pool.execute(
        "INSERT INTO memories (
            id, memory_type, status, claim, source_episodes_json, source_events_json,
            domains_json, salience_json, confidence, authority, applies_when_json,
            does_not_apply_when_json, created_at, updated_at
        ) VALUES (
            ?1, 'semantic', 'active', ?2,
            '[]', '[\"evt_restore_candidate\"]', '[]', json_object('score', ?3), 0.7, 'verified',
            '[]', '[]', '2026-05-04T12:00:00Z', '2026-05-04T12:00:00Z'
        );",
        rusqlite::params![id, claim, score],
    )
    .expect("insert active memory");
}

fn base_snapshot(id: &str) -> serde_json::Value {
    json!({
        "snapshot_id": id,
        "schema_version": 2,
        "truth_ceiling": {
            "runtime_mode": "signed_local_ledger",
            "proof_state": "full_chain_verified",
            "claim_ceiling": "trusted_local_ledger"
        }
    })
}

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

    let out = run_in(tmp.path(), &["restore", "snapshot"]);

    assert_exit(&out, 0);
    let snapshot: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(snapshot["snapshot_id"], "store-current");
    assert_eq!(snapshot["schema_version"], serde_json::Value::Null);
    assert_eq!(snapshot["active_memories"], json!({}));
    assert_eq!(snapshot["active_doctrine"], json!({}));
    assert_eq!(snapshot["unresolved_contradictions"], json!({}));
}

#[test]
fn restore_snapshot_extracts_candidate_store_read_only() {
    let tmp = tempfile::tempdir().unwrap();
    let db = init_store(tmp.path());
    let pool = apply_store_migrations(&db);
    insert_active_memory(
        &pool,
        "mem_restore_candidate",
        "Candidate restore snapshot extraction is read-only.",
        0.4,
    );

    let out = run(&["restore", "snapshot", "--store", db.to_str().unwrap()]);

    assert_exit(&out, 0);
    let snapshot: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(snapshot["snapshot_id"], "store-current");
    assert_eq!(
        snapshot["active_memories"]["mem_restore_candidate"]["claim"],
        "Candidate restore snapshot extraction is read-only."
    );
    assert_eq!(
        snapshot["active_memories"]["mem_restore_candidate"]["salience"],
        40
    );
    assert_eq!(snapshot["salience_distribution"]["medium"], 1);
}

#[test]
fn restore_semantic_diff_compares_candidate_stores_read_only() {
    let tmp = tempfile::tempdir().unwrap();
    let current_root = tmp.path().join("current");
    let restored_root = tmp.path().join("restored");
    fs::create_dir_all(&current_root).unwrap();
    fs::create_dir_all(&restored_root).unwrap();
    let current_db = init_store(&current_root);
    let restored_db = init_store(&restored_root);
    let current_pool = apply_store_migrations(&current_db);
    apply_store_migrations(&restored_db);
    insert_active_memory(
        &current_pool,
        "mem_restore_current",
        "Direct store semantic diff must see removed active memories.",
        0.8,
    );

    let out = run(&[
        "restore",
        "semantic-diff",
        "--current-store",
        current_db.to_str().unwrap(),
        "--restored-store",
        restored_db.to_str().unwrap(),
    ]);

    assert_exit(&out, 7);
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["command"], "restore.semantic_diff");
    assert_eq!(report["severity"], "precondition_unmet");
    assert_eq!(report["mutated_store"], false);
    assert!(
        out.stdout
            .windows("active_memory_missing".len())
            .any(|window| window == b"active_memory_missing"),
        "stdout should name removed memory category: {}",
        String::from_utf8_lossy(&out.stdout)
    );
}

#[test]
fn restore_semantic_diff_clean_snapshots_pass_without_mutation() {
    let tmp = tempfile::tempdir().unwrap();
    let current = tmp.path().join("current.json");
    let restored = tmp.path().join("restored.json");
    write_json(&current, base_snapshot("snap-a"));
    write_json(&restored, base_snapshot("snap-b"));

    let out = run(&[
        "restore",
        "semantic-diff",
        "--current",
        current.to_str().unwrap(),
        "--restored",
        restored.to_str().unwrap(),
    ]);

    assert_exit(&out, 0);
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["command"], "restore.semantic_diff");
    assert_eq!(report["severity"], "clean");
    assert_eq!(report["change_count"], 0);
    assert_eq!(report["mutated_store"], false);
}

#[test]
fn restore_semantic_diff_blocks_truth_ceiling_downgrade() {
    let tmp = tempfile::tempdir().unwrap();
    let current = tmp.path().join("current.json");
    let restored = tmp.path().join("restored.json");
    write_json(&current, base_snapshot("snap-current"));
    let mut restored_json = base_snapshot("snap-restored");
    restored_json["truth_ceiling"]["claim_ceiling"] = json!("advisory");
    write_json(&restored, restored_json);

    let out = run(&[
        "restore",
        "semantic-diff",
        "--current",
        current.to_str().unwrap(),
        "--restored",
        restored.to_str().unwrap(),
    ]);

    assert_exit(&out, 7);
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["severity"], "precondition_unmet");
    assert_eq!(report["mutated_store"], false);
    assert!(
        out.stdout
            .windows("truth_ceiling_downgraded".len())
            .any(|window| window == b"truth_ceiling_downgraded"),
        "stdout should name downgrade category: {}",
        String::from_utf8_lossy(&out.stdout)
    );
}

#[test]
fn restore_semantic_diff_malformed_snapshot_fails_closed() {
    let tmp = tempfile::tempdir().unwrap();
    let current = tmp.path().join("current.json");
    let restored = tmp.path().join("restored.json");
    fs::write(&current, b"{not-json").unwrap();
    write_json(&restored, base_snapshot("snap-restored"));

    let out = run(&[
        "restore",
        "semantic-diff",
        "--current",
        current.to_str().unwrap(),
        "--restored",
        restored.to_str().unwrap(),
    ]);

    assert_exit(&out, 5);
    assert!(out.stdout.is_empty());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("failed to parse current snapshot"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_verify_backup_accepts_pre_v2_manifest_without_mutation() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));

    let out = run(&[
        "restore",
        "verify-backup",
        "--manifest",
        manifest.to_str().unwrap(),
    ]);

    assert_exit(&out, 0);
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["command"], "restore.verify_backup");
    assert_eq!(report["kind"], "cortex_pre_v2_backup");
    assert_eq!(report["schema_version"], 1);
    assert_eq!(report["restore_performed"], false);
    assert_eq!(report["cutover_performed"], false);
    assert_eq!(report["destructive_restore_supported"], false);
    assert_eq!(report["mutated_store"], false);
    assert_eq!(report["artifacts"][0]["field"], "sqlite_store");
    assert_eq!(report["artifacts"][1]["field"], "jsonl_mirror");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("destructive restore/cutover is not implemented"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_preflight_reports_semantic_diff_pending_without_candidate_store() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));

    let out = run(&[
        "restore",
        "preflight",
        "--manifest",
        manifest.to_str().unwrap(),
    ]);

    assert_exit(&out, 7);
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["command"], "restore.preflight");
    assert_eq!(report["structural_verification"]["status"], "verified");
    assert_eq!(report["semantic_diff"]["required"], true);
    assert_eq!(report["semantic_diff"]["executed"], false);
    assert_eq!(report["semantic_diff"]["status"], "required_not_executed");
    assert_eq!(report["restore_performed"], false);
    assert_eq!(report["cutover_performed"], false);
    assert_eq!(report["mutated_store"], false);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("no state was changed"), "stderr: {stderr}");
}

#[test]
fn restore_preflight_runs_clean_semantic_diff_against_candidate_store_read_only() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let current_root = tmp.path().join("current");
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&current_root).unwrap();
    fs::create_dir_all(&candidate_root).unwrap();
    let current_db = init_store(&current_root);
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&current_db);
    apply_store_migrations(&candidate_db);

    let out = run(&[
        "restore",
        "preflight",
        "--manifest",
        manifest.to_str().unwrap(),
        "--current-store",
        current_db.to_str().unwrap(),
        "--candidate-store",
        candidate_db.to_str().unwrap(),
    ]);

    assert_exit(&out, 0);
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["command"], "restore.preflight");
    assert_eq!(report["structural_verification"]["status"], "verified");
    assert_eq!(report["semantic_diff"]["required"], true);
    assert_eq!(report["semantic_diff"]["executed"], true);
    assert_eq!(report["semantic_diff"]["status"], "clean");
    assert_eq!(report["semantic_diff"]["change_count"], 0);
    assert_eq!(report["restore_performed"], false);
    assert_eq!(report["cutover_performed"], false);
    assert_eq!(report["mutated_store"], false);
}

#[test]
fn restore_preflight_production_plan_acquires_releases_temp_lock_without_mutation() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let current_root = tmp.path().join("current");
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&current_root).unwrap();
    fs::create_dir_all(&candidate_root).unwrap();
    let current_db = init_store(&current_root);
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&current_db);
    apply_store_migrations(&candidate_db);
    let before = read_active_artifacts(&current_db);
    let lock_marker = current_db
        .parent()
        .unwrap()
        .join(".cortex-restore-active-store.lock");
    assert!(!lock_marker.exists());

    let out = run(&[
        "restore",
        "preflight",
        "--manifest",
        manifest.to_str().unwrap(),
        "--current-store",
        current_db.to_str().unwrap(),
        "--candidate-store",
        candidate_db.to_str().unwrap(),
        "--production-active-store-plan",
    ]);

    assert_exit(&out, 7);
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["command"], "restore.preflight");
    assert_eq!(report["structural_verification"]["status"], "verified");
    assert_eq!(report["semantic_diff"]["status"], "clean");
    assert_eq!(report["production_active_store_plan"]["requested"], true);
    assert_eq!(report["production_active_store_plan"]["status"], "blocked");
    assert_eq!(
        report["production_active_store_plan"]["mutation_supported"],
        false
    );
    assert_eq!(
        report["production_active_store_plan"]["preflight_gates"]["semantic_diff"],
        "satisfied"
    );
    assert_eq!(
        report["production_active_store_plan"]["preflight_gates"]["active_store_lock"],
        "temp_lock_acquire_release_verified"
    );
    assert_eq!(
        report["production_active_store_plan"]["preflight_gates"]["schema_v2_cutover"],
        "blocked"
    );
    assert_eq!(
        report["production_active_store_plan"]["preflight_gates"]["post_restore_verification"],
        "blocked"
    );
    assert_eq!(
        report["production_active_store_plan"]["post_restore_verification_gates"]["status"],
        "blocked"
    );
    assert_eq!(
        report["production_active_store_plan"]["post_restore_verification_gates"]["anchors"]
            ["status"],
        "missing_external_anchor_authority"
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]["marker_exists"],
        false
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]["absence_satisfied"],
        true
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]["exclusive_lock_acquired"],
        false
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]
            ["exclusive_lock_acquire_attempted"],
        true
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]
            ["exclusive_lock_acquired_during_probe"],
        true
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]["exclusive_lock_released"],
        true
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]
            ["exclusive_lock_acquire_release_verified"],
        true
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]["lock_marker"].as_str(),
        Some(lock_marker.to_string_lossy().as_ref())
    );
    assert!(
        !lock_marker.exists(),
        "lock probe must release the temp-test marker"
    );
    assert!(
        report["production_active_store_plan"]["required_gates"]
            .as_array()
            .unwrap()
            .iter()
            .any(|gate| gate["gate"] == "active_store_lock"),
        "production plan must name the active-store lock gate: {}",
        String::from_utf8_lossy(&out.stdout)
    );
    assert!(
        report["production_active_store_plan"]["required_gates"]
            .as_array()
            .unwrap()
            .iter()
            .any(|gate| gate["gate"] == "schema_v2_cutover"),
        "production plan must name the schema v2 blocker: {}",
        String::from_utf8_lossy(&out.stdout)
    );
    assert_eq!(report["restore_performed"], false);
    assert_eq!(report["cutover_performed"], false);
    assert_eq!(report["mutated_store"], false);
    assert_eq!(read_active_artifacts(&current_db), before);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("production active-store restore plan is blocked")
            && stderr.contains("no state was changed"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_preflight_production_plan_reports_existing_active_store_lock_marker() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let current_root = tmp.path().join("current");
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&current_root).unwrap();
    fs::create_dir_all(&candidate_root).unwrap();
    let current_db = init_store(&current_root);
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&current_db);
    apply_store_migrations(&candidate_db);
    let lock_marker = tmp.path().join("active-store.lock");
    fs::write(&lock_marker, b"held-by-test\n").unwrap();
    let before = read_active_artifacts(&current_db);

    let out = run(&[
        "restore",
        "preflight",
        "--manifest",
        manifest.to_str().unwrap(),
        "--current-store",
        current_db.to_str().unwrap(),
        "--candidate-store",
        candidate_db.to_str().unwrap(),
        "--production-active-store-plan",
        "--active-store-lock-marker",
        lock_marker.to_str().unwrap(),
    ]);

    assert_exit(&out, 7);
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["command"], "restore.preflight");
    assert_eq!(
        report["production_active_store_plan"]["preflight_gates"]["active_store_lock"],
        "blocked_existing_lock_marker"
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]["lock_marker"].as_str(),
        Some(lock_marker.to_string_lossy().as_ref())
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]["marker_exists"],
        true
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]["absence_satisfied"],
        false
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]["exclusive_lock_acquired"],
        false
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]
            ["exclusive_lock_acquire_attempted"],
        false
    );
    assert_eq!(
        report["production_active_store_plan"]["active_store_lock"]
            ["exclusive_lock_acquire_release_verified"],
        false
    );
    assert_eq!(report["restore_performed"], false);
    assert_eq!(report["cutover_performed"], false);
    assert_eq!(report["mutated_store"], false);
    assert_eq!(read_active_artifacts(&current_db), before);
    assert_eq!(fs::read(&lock_marker).unwrap(), b"held-by-test\n");
}

#[test]
fn restore_verify_backup_rejects_wrong_manifest_kind() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let mut value: serde_json::Value =
        serde_json::from_slice(&fs::read(&manifest).unwrap()).unwrap();
    value["kind"] = json!("cortex_untrusted_backup");
    write_json(&manifest, value);

    let out = run(&[
        "restore",
        "verify-backup",
        "--manifest",
        manifest.to_str().unwrap(),
    ]);

    assert_exit(&out, 7);
    assert!(out.stdout.is_empty());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("expected cortex_pre_v2_backup") && stderr.contains("no state was changed"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_verify_backup_rejects_missing_digest_fields() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let mut value: serde_json::Value =
        serde_json::from_slice(&fs::read(&manifest).unwrap()).unwrap();
    value.as_object_mut().unwrap().remove("jsonl_mirror_blake3");
    write_json(&manifest, value);

    let out = run(&[
        "restore",
        "verify-backup",
        "--manifest",
        manifest.to_str().unwrap(),
    ]);

    assert_exit(&out, 7);
    assert!(out.stdout.is_empty());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("malformed") && stderr.contains("jsonl_mirror_blake3"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_verify_backup_rejects_artifact_digest_mismatch() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let jsonl = manifest.parent().unwrap().join("events.jsonl");
    let original_len = fs::metadata(&jsonl).unwrap().len() as usize;
    fs::write(&jsonl, vec![b'x'; original_len]).unwrap();

    let out = run(&[
        "restore",
        "verify-backup",
        "--manifest",
        manifest.to_str().unwrap(),
    ]);

    assert_exit(&out, 5);
    assert!(out.stdout.is_empty());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("digest mismatch") && stderr.contains("no state was changed"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_stage_requires_acknowledgement_without_mutation() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let stage_dir = tmp.path().join("stage");

    let out = run(&[
        "restore",
        "stage",
        "--manifest",
        manifest.to_str().unwrap(),
        "--stage-dir",
        stage_dir.to_str().unwrap(),
    ]);

    assert_exit(&out, 7);
    assert!(out.stdout.is_empty());
    assert!(
        !stage_dir.exists(),
        "stage directory must not be created without acknowledgement"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--acknowledge-destructive-restore")
            && stderr.contains("no state was changed"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_stage_rejects_corrupt_backup_before_staging() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let jsonl = manifest.parent().unwrap().join("events.jsonl");
    let original_len = fs::metadata(&jsonl).unwrap().len() as usize;
    fs::write(&jsonl, vec![b'x'; original_len]).unwrap();
    let stage_dir = tmp.path().join("stage");

    let out = run(&[
        "restore",
        "stage",
        "--manifest",
        manifest.to_str().unwrap(),
        "--stage-dir",
        stage_dir.to_str().unwrap(),
        "--acknowledge-destructive-restore",
    ]);

    assert_exit(&out, 5);
    assert!(out.stdout.is_empty());
    assert!(
        !stage_dir.exists(),
        "stage directory must not be created for a corrupt backup"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("digest mismatch") && stderr.contains("no state was changed"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_stage_copies_then_audit_verifies_and_semantic_preflights_candidate() {
    let tmp = tempfile::tempdir().unwrap();
    let current_root = tmp.path().join("current");
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&current_root).unwrap();
    fs::create_dir_all(&candidate_root).unwrap();
    let current_db = init_store(&current_root);
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&current_db);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let anchor = current_anchor(&candidate_log, Utc::now()).unwrap();
    let anchor_path = tmp.path().join("RESTORE_ANCHOR");
    fs::write(&anchor_path, anchor.to_anchor_text()).unwrap();
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");

    let out = run(&[
        "restore",
        "stage",
        "--manifest",
        manifest.to_str().unwrap(),
        "--stage-dir",
        stage_dir.to_str().unwrap(),
        "--current-store",
        current_db.to_str().unwrap(),
        "--acknowledge-destructive-restore",
    ]);

    assert_exit(&out, 0);
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["command"], "restore.stage");
    assert_eq!(report["structural_verification"]["status"], "verified");
    assert_eq!(report["audit_verification"]["status"], "verified");
    assert_eq!(report["audit_verification"]["rows_scanned"], 1);
    assert_eq!(report["semantic_diff"]["executed"], true);
    assert_eq!(report["semantic_diff"]["status"], "clean");
    assert_eq!(report["destructive_restore_staged"], true);
    assert_eq!(report["restore_performed"], false);
    assert_eq!(report["cutover_performed"], false);
    assert_eq!(report["mutated_store"], false);
    assert!(stage_dir.join("cortex.db").is_file());
    assert!(stage_dir.join("events.jsonl").is_file());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("active store was not changed"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_apply_stage_requires_acknowledgement_without_mutating_active_store() {
    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let before = read_active_artifacts(&active_db);
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    assert!(out.stdout.is_empty());
    assert_eq!(read_active_artifacts(&active_db), before);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--acknowledge-active-store-replacement")
            && stderr.contains("--acknowledge-temp-test-data-dir")
            && stderr.contains("active store was not changed"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_apply_stage_rejects_corrupt_stage_without_mutating_active_store() {
    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let before = read_active_artifacts(&active_db);
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);
    let staged_log = stage_dir.join("events.jsonl");
    let original_len = fs::metadata(&staged_log).unwrap().len() as usize;
    fs::write(&staged_log, vec![b'x'; original_len]).unwrap();

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--acknowledge-active-store-replacement",
            "--acknowledge-temp-test-data-dir",
        ],
    );

    assert_exit(&out, 5);
    assert!(out.stdout.is_empty());
    assert_eq!(read_active_artifacts(&active_db), before);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("digest mismatch") && stderr.contains("active store was not changed"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_apply_stage_fails_closed_when_recovery_evidence_exists() {
    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let before = read_active_artifacts(&active_db);
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);
    fs::create_dir(apply_recovery_dir(&active_db)).unwrap();

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--acknowledge-active-store-replacement",
            "--acknowledge-temp-test-data-dir",
        ],
    );

    assert_exit(&out, 7);
    assert!(out.stdout.is_empty());
    assert_eq!(read_active_artifacts(&active_db), before);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("recovery evidence directory")
            && stderr.contains("active store was not changed"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_apply_stage_applies_clean_candidate_in_temp_test_data_dir() {
    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let before = read_active_artifacts(&active_db);
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--acknowledge-active-store-replacement",
            "--acknowledge-temp-test-data-dir",
        ],
    );

    assert_exit(&out, 0);
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["command"], "restore.apply_stage");
    assert_eq!(report["structural_verification"]["status"], "verified");
    assert_eq!(report["staged_artifacts"], "verified");
    assert_eq!(report["audit_verification"]["status"], "verified");
    assert_eq!(report["semantic_diff"]["status"], "clean");
    assert_eq!(
        report["recovery_evidence"]["status"],
        "prepared_before_active_replacement"
    );
    assert_eq!(
        report["post_restore_verification"]["manifest_artifacts"]["status"],
        "source_verified_active_jsonl_verified_sqlite_payload_semantically_verified"
    );
    assert_eq!(
        report["post_restore_verification"]["manifest_artifacts"]["jsonl_mirror"]["status"],
        "active_digest_verified"
    );
    assert_eq!(
        report["post_restore_verification"]["manifest_artifacts"]["sqlite_store"]
            ["active_exact_digest"],
        "not_claimed_final_sqlite_contains_command_audit_row"
    );
    assert_eq!(
        report["post_restore_verification"]["manifest_artifacts"]["sqlite_store"]
            ["final_active_digest_claimed"],
        false
    );
    assert_eq!(
        report["post_restore_verification"]["jsonl_audit"]["status"],
        "verified"
    );
    assert_eq!(
        report["post_restore_verification"]["semantic_diff"]["status"],
        "clean"
    );
    assert_eq!(
        report["post_restore_verification"]["semantic_diff"]["comparison"],
        "staged_candidate_to_restored_active_store"
    );
    assert_eq!(
        report["post_restore_verification"]["anchors"]["status"],
        "not_configured"
    );
    assert_eq!(
        report["post_restore_verification"]["anchors"]["single_anchor"],
        serde_json::Value::Null
    );
    assert_eq!(
        report["post_restore_verification"]["anchors"]["production_anchor_authority"],
        false
    );
    assert_eq!(
        report["post_restore_verification"]["production_eligible"],
        false
    );
    assert_eq!(report["restore_performed"], true);
    assert_eq!(report["cutover_performed"], true);
    assert_eq!(report["mutated_store"], true);
    assert_eq!(report["audit_operation"], "command.restore.apply_stage");
    assert_eq!(audit_count(&active_db, "command.restore.apply_stage"), 1);
    let audit_refs = audit_source_refs(&active_db, "command.restore.apply_stage");
    let (_, after_hash) = audit_hashes(&active_db, "command.restore.apply_stage");
    assert_eq!(
        after_hash,
        audit_refs["sqlite_store_blake3"].as_str().unwrap()
    );
    assert_eq!(
        audit_refs["manifest"].as_str(),
        Some(manifest.to_string_lossy().as_ref())
    );
    assert_eq!(
        audit_refs["after_hash_semantics"],
        "verified restored SQLite payload before command audit row append; final active SQLite digest is not self-claimed by the row"
    );
    assert_eq!(audit_refs["scope"], "temp-test");
    let recovery_manifest =
        PathBuf::from(report["recovery_evidence"]["manifest"].as_str().unwrap());
    let active_db_backup = PathBuf::from(
        report["recovery_evidence"]["active_db_backup"]
            .as_str()
            .unwrap(),
    );
    let active_event_log_backup = PathBuf::from(
        report["recovery_evidence"]["active_event_log_backup"]
            .as_str()
            .unwrap(),
    );
    assert!(recovery_manifest.is_file());
    assert_eq!(fs::read(&active_db_backup).unwrap(), before.0);
    assert_eq!(fs::read(&active_event_log_backup).unwrap(), before.1);
    let manifest_json: serde_json::Value =
        serde_json::from_slice(&fs::read(recovery_manifest).unwrap()).unwrap();
    assert_eq!(
        manifest_json["kind"],
        "cortex_restore_apply_stage_recovery_manifest"
    );
    assert_eq!(manifest_json["scope"], "temp-test");
    assert_eq!(
        manifest_json["status"],
        "prepared_before_active_replacement"
    );
    assert_ne!(
        fs::read(&active_db).unwrap(),
        fs::read(stage_dir.join("cortex.db")).unwrap(),
        "active SQLite store should include the persisted apply-stage command audit row"
    );
    assert_eq!(
        fs::read(active_db.parent().unwrap().join("events.jsonl")).unwrap(),
        fs::read(stage_dir.join("events.jsonl")).unwrap()
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("active store was mutated"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_apply_stage_rolls_back_when_post_restore_anchor_verification_fails() {
    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let before = read_active_artifacts(&active_db);
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);

    let stale_anchor = current_anchor(&candidate_log, Utc::now()).unwrap();
    let stale_anchor_text = stale_anchor.to_anchor_text().replace(
        &stale_anchor.chain_head_hash,
        "0000000000000000000000000000000000000000000000000000000000000000",
    );
    let stale_anchor_path = tmp.path().join("STALE_RESTORE_ANCHOR");
    fs::write(&stale_anchor_path, stale_anchor_text).unwrap();

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--acknowledge-active-store-replacement",
            "--acknowledge-temp-test-data-dir",
            "--post-restore-anchor",
            stale_anchor_path.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 3);
    assert!(out.stdout.is_empty());
    assert_eq!(read_active_artifacts(&active_db), before);
    let recovery_dir = apply_recovery_dir(&active_db);
    assert!(
        recovery_dir.join("RECOVERY_MANIFEST.json").is_file(),
        "failed post-restore verification should leave recovery evidence for operator audit"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("post-restore anchor verification failed")
            && stderr.contains("active backups were restored")
            && stderr.contains("pre-apply state"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_recover_apply_requires_acknowledgement_without_mutating_active_store() {
    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);
    let apply = run_in(
        tmp.path(),
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--acknowledge-active-store-replacement",
            "--acknowledge-temp-test-data-dir",
        ],
    );
    assert_exit(&apply, 0);
    let apply_report: serde_json::Value = serde_json::from_slice(&apply.stdout).unwrap();
    let recovery_manifest = PathBuf::from(
        apply_report["recovery_evidence"]["manifest"]
            .as_str()
            .unwrap(),
    );
    let after_apply = read_active_artifacts(&active_db);

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "recover-apply",
            "--manifest",
            recovery_manifest.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    assert!(out.stdout.is_empty());
    assert_eq!(read_active_artifacts(&active_db), after_apply);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--acknowledge-current-backup-restore")
            && stderr.contains("--acknowledge-temp-test-data-dir")
            && stderr.contains("active store was not changed"),
        "stderr: {stderr}"
    );
}

#[cfg(unix)]
#[test]
fn restore_recover_apply_rejects_symlinked_active_target_without_writing_through() {
    use std::os::unix::fs::symlink;

    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);
    let apply = run_in(
        tmp.path(),
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--acknowledge-active-store-replacement",
            "--acknowledge-temp-test-data-dir",
        ],
    );
    assert_exit(&apply, 0);
    let apply_report: serde_json::Value = serde_json::from_slice(&apply.stdout).unwrap();
    let recovery_manifest = PathBuf::from(
        apply_report["recovery_evidence"]["manifest"]
            .as_str()
            .unwrap(),
    );

    let outside_target = tmp.path().join("outside-target.db");
    fs::write(&outside_target, b"outside target must not be overwritten").unwrap();
    fs::remove_file(&active_db).unwrap();
    symlink(&outside_target, &active_db).unwrap();
    let outside_before = fs::read(&outside_target).unwrap();

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "recover-apply",
            "--manifest",
            recovery_manifest.to_str().unwrap(),
            "--acknowledge-current-backup-restore",
            "--acknowledge-temp-test-data-dir",
        ],
    );

    assert_exit(&out, 7);
    assert!(out.stdout.is_empty());
    assert_eq!(
        fs::read(&outside_target).unwrap(),
        outside_before,
        "recover-apply must not write through a symlinked active SQLite target"
    );
    assert!(
        fs::symlink_metadata(&active_db)
            .unwrap()
            .file_type()
            .is_symlink(),
        "failed recovery must leave the symlink target untouched for operator inspection"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("active SQLite path")
            && stderr.contains("is a symlink")
            && stderr.contains("active store was not changed"),
        "stderr: {stderr}"
    );
}

#[cfg(unix)]
#[test]
fn restore_recover_apply_rejects_symlinked_active_jsonl_without_writing_through() {
    use std::os::unix::fs::symlink;

    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let active_jsonl = active_db.parent().unwrap().join("events.jsonl");
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);
    let apply = run_in(
        tmp.path(),
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--acknowledge-active-store-replacement",
            "--acknowledge-temp-test-data-dir",
        ],
    );
    assert_exit(&apply, 0);
    let apply_report: serde_json::Value = serde_json::from_slice(&apply.stdout).unwrap();
    let recovery_manifest = PathBuf::from(
        apply_report["recovery_evidence"]["manifest"]
            .as_str()
            .unwrap(),
    );

    let outside_target = tmp.path().join("outside-target.events.jsonl");
    fs::write(&outside_target, b"outside target must not be overwritten").unwrap();
    fs::remove_file(&active_jsonl).unwrap();
    symlink(&outside_target, &active_jsonl).unwrap();
    let outside_before = fs::read(&outside_target).unwrap();

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "recover-apply",
            "--manifest",
            recovery_manifest.to_str().unwrap(),
            "--acknowledge-current-backup-restore",
            "--acknowledge-temp-test-data-dir",
        ],
    );

    assert_exit(&out, 7);
    assert!(out.stdout.is_empty());
    assert_eq!(
        fs::read(&outside_target).unwrap(),
        outside_before,
        "recover-apply must not write through a symlinked active JSONL target"
    );
    assert!(
        fs::symlink_metadata(&active_jsonl)
            .unwrap()
            .file_type()
            .is_symlink(),
        "failed recovery must leave the symlink target untouched for operator inspection"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("active JSONL path")
            && stderr.contains("is a symlink")
            && stderr.contains("active store was not changed"),
        "stderr: {stderr}"
    );
}

#[test]
fn restore_recover_apply_restores_current_backups_from_apply_recovery_manifest() {
    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let before = read_active_artifacts(&active_db);
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);
    let apply = run_in(
        tmp.path(),
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--acknowledge-active-store-replacement",
            "--acknowledge-temp-test-data-dir",
        ],
    );
    assert_exit(&apply, 0);
    let apply_report: serde_json::Value = serde_json::from_slice(&apply.stdout).unwrap();
    let recovery_manifest = PathBuf::from(
        apply_report["recovery_evidence"]["manifest"]
            .as_str()
            .unwrap(),
    );
    assert_ne!(read_active_artifacts(&active_db), before);

    // Phase 2.6: recover-apply now requires --attestation and seeded
    // operator-key timeline rows for the bound key. Mirror what
    // `cli_phase2::seed_operator_authority` does for `cortex principle
    // promote`.
    let (attestation_key, attestor) = restore_attestation_key_fixture(tmp.path());
    seed_operator_authority_for_restore(&active_db, &attestor);

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "recover-apply",
            "--manifest",
            recovery_manifest.to_str().unwrap(),
            "--acknowledge-current-backup-restore",
            "--acknowledge-temp-test-data-dir",
            "--attestation",
            attestation_key.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 0);
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["command"], "restore.recover_apply");
    assert_eq!(report["scope"], "temp-test");
    assert_eq!(
        report["recovery_status"],
        "current_backups_restored_with_command_audit_row"
    );
    assert_eq!(report["restore_performed"], true);
    assert_eq!(report["cutover_performed"], true);
    assert_eq!(report["mutated_store"], true);
    assert_eq!(report["audit_operation"], "command.restore.recover_apply");
    assert_eq!(audit_count(&active_db, "command.restore.recover_apply"), 1);
    let audit_refs = audit_source_refs(&active_db, "command.restore.recover_apply");
    let (_, after_hash) = audit_hashes(&active_db, "command.restore.recover_apply");
    assert_eq!(
        after_hash,
        audit_refs["active_db_backup_blake3"].as_str().unwrap()
    );
    assert_eq!(
        audit_refs["manifest"].as_str(),
        Some(recovery_manifest.to_string_lossy().as_ref())
    );
    assert_eq!(audit_refs["scope"], "temp-test");
    assert_eq!(
        audit_refs["after_hash_semantics"],
        "verified recovered SQLite backup payload before command audit row append; final active SQLite digest is not self-claimed by the row"
    );
    assert_ne!(
        fs::read(&active_db).unwrap(),
        before.0,
        "recovered SQLite store should include the persisted recover-apply command audit row"
    );
    assert_eq!(
        fs::read(active_db.parent().unwrap().join("events.jsonl")).unwrap(),
        before.1
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("current backups restored") && stderr.contains("active store was mutated"),
        "stderr: {stderr}"
    );
}

// =============================================================================
// `restore apply --production --anchor-sink rekor` whitelist tests.
//
// Authorized by `docs/council-briefings/COUNCIL_2026-05-12_production_restore_evidence.md`
// Q1 (UNANIMOUS) + operator tiebreak 2026-05-12.
//
// These tests exercise the sink-kind whitelist gate added to
// `crates/cortex-cli/src/cmd/restore/production.rs`. A full end-to-end
// happy-path drill is exercised by the restore-drill scripts; here we
// pin the new fail-closed invariants.
// =============================================================================

/// Minimal helper: place a directory at `path` so `--stage-dir` passes the
/// `is_dir()` check, and stub the artifacts a later validation step would
/// expect. We rely on the sink-kind check firing before any of those
/// later validations write to the active store.
fn production_apply_stage_dir(base: &Path) -> PathBuf {
    let stage = base.join("stage");
    fs::create_dir_all(&stage).unwrap();
    fs::write(stage.join("cortex.db"), b"placeholder-sqlite").unwrap();
    fs::write(stage.join("events.jsonl"), b"{}\n").unwrap();
    stage
}

fn dummy_path(base: &Path, name: &str) -> PathBuf {
    let path = base.join(name);
    fs::write(&path, b"placeholder").unwrap();
    path
}

#[test]
fn production_restore_rejects_unknown_sink_kind() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let stage = production_apply_stage_dir(tmp.path());
    let restore_intent = dummy_path(tmp.path(), "RESTORE_INTENT.json");
    let restore_intent_sig = dummy_path(tmp.path(), "RESTORE_INTENT.sig");
    let operator_key = dummy_path(tmp.path(), "operator.pubkey");
    let anchor_path = dummy_path(tmp.path(), "ANCHOR.json");
    let anchor_history_path = dummy_path(tmp.path(), "ANCHOR_HISTORY");
    let sink_path = tmp.path().join("sink");

    let out = run(&[
        "restore",
        "apply",
        "--production",
        "--manifest",
        manifest.to_str().unwrap(),
        "--stage-dir",
        stage.to_str().unwrap(),
        "--restore-intent",
        restore_intent.to_str().unwrap(),
        "--restore-intent-signature",
        restore_intent_sig.to_str().unwrap(),
        "--operator-verification-key",
        operator_key.to_str().unwrap(),
        "--against",
        anchor_path.to_str().unwrap(),
        "--against-history",
        anchor_history_path.to_str().unwrap(),
        "--anchor-sink",
        "definitely-not-a-real-sink",
        "--sink-path",
        sink_path.to_str().unwrap(),
        "--acknowledge-production-destructive-restore",
        "--acknowledge-active-store-replacement",
    ]);

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("restore.production.sink_kind.unknown"),
        "stable invariant token must surface; stderr: {stderr}"
    );
    assert!(
        stderr.contains("active store was not changed"),
        "fail-closed clause must surface; stderr: {stderr}"
    );
    assert!(!sink_path.exists(), "no sink artifact may be written");
}

#[test]
fn production_restore_refuses_legacy_external_append_only_sink_at_parser() {
    // Finding F1 closure
    // (`docs/reviews/CODE_REVIEW_2026-05-12_post_8f43450.md`): Council Q1
    // (2026-05-12) made Rekor the disjoint-authority gate for production
    // destructive restore. `--anchor-sink external-append-only` must
    // refuse at the parser BEFORE any active-store mutation, intent
    // verification, lock acquisition, or witness emission.
    let tmp = tempfile::tempdir().unwrap();

    // Initialize a real active store so we can assert it is untouched
    // by the parser-level refusal (same sentinel pattern as
    // `production_restore_refuses_principal_not_bound_to_verifying_key`).
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let active_jsonl = active_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&active_jsonl);
    let active_db_bytes_before = fs::read(&active_db).unwrap();
    let active_jsonl_bytes_before = fs::read(&active_jsonl).unwrap();

    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let stage = production_apply_stage_dir(tmp.path());
    let restore_intent = dummy_path(tmp.path(), "RESTORE_INTENT.json");
    let restore_intent_sig = dummy_path(tmp.path(), "RESTORE_INTENT.sig");
    let operator_key = dummy_path(tmp.path(), "operator.pubkey");
    let anchor_path = dummy_path(tmp.path(), "ANCHOR.json");
    let anchor_history_path = dummy_path(tmp.path(), "ANCHOR_HISTORY");
    // Sink path is a placeholder that exists; the legacy sink kind
    // must be refused regardless of whether the sink path is present.
    let sink_path = dummy_path(tmp.path(), "sink");
    let sink_bytes_before = fs::read(&sink_path).unwrap();

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "apply",
            "--production",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage.to_str().unwrap(),
            "--restore-intent",
            restore_intent.to_str().unwrap(),
            "--restore-intent-signature",
            restore_intent_sig.to_str().unwrap(),
            "--operator-verification-key",
            operator_key.to_str().unwrap(),
            "--against",
            anchor_path.to_str().unwrap(),
            "--against-history",
            anchor_history_path.to_str().unwrap(),
            "--anchor-sink",
            "external-append-only",
            "--sink-path",
            sink_path.to_str().unwrap(),
            "--acknowledge-production-destructive-restore",
            "--acknowledge-active-store-replacement",
        ],
    );

    // Exit::PreconditionUnmet == 7. The refusal must fire before any
    // mutation, so the exit code must be non-zero.
    let code = out.status.code().expect("process exited via signal");
    assert_ne!(
        code,
        0,
        "legacy sink kind must refuse; stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    assert_exit(&out, 7);

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("restore.production.sink_kind.external_append_only_not_authorized"),
        "stable invariant token must surface; stderr: {stderr}"
    );
    assert!(
        stderr.contains("active store was not changed"),
        "fail-closed clause must surface; stderr: {stderr}"
    );
    // Operator guidance must point at the authorized sink.
    assert!(
        stderr.contains("--anchor-sink `rekor`") || stderr.contains("--anchor-sink rekor"),
        "operator guidance to rekor must surface; stderr: {stderr}"
    );

    // The active store must be unchanged by a parser-level refusal.
    assert_eq!(
        fs::read(&active_db).unwrap(),
        active_db_bytes_before,
        "parser-level refusal must not mutate the active SQLite store",
    );
    assert_eq!(
        fs::read(&active_jsonl).unwrap(),
        active_jsonl_bytes_before,
        "parser-level refusal must not mutate the active JSONL log",
    );
    // The placeholder sink bytes must be untouched (no witness emission).
    assert_eq!(
        fs::read(&sink_path).unwrap(),
        sink_bytes_before,
        "parser-level refusal must not emit a sink witness",
    );
}

#[test]
fn production_restore_rekor_sink_rejects_missing_parent_directory() {
    // Operator passes a `--sink-path` whose parent does not exist. The
    // sink-kind gate accepts `rekor`, but the parent-dir precheck
    // fails closed before any cutover.
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let stage = production_apply_stage_dir(tmp.path());
    let restore_intent = dummy_path(tmp.path(), "RESTORE_INTENT.json");
    let restore_intent_sig = dummy_path(tmp.path(), "RESTORE_INTENT.sig");
    let operator_key = dummy_path(tmp.path(), "operator.pubkey");
    let anchor_path = dummy_path(tmp.path(), "ANCHOR.json");
    let anchor_history_path = dummy_path(tmp.path(), "ANCHOR_HISTORY");
    // Parent dir is intentionally not created.
    let sink_path = tmp.path().join("missing").join("receipt.json");

    let out = run(&[
        "restore",
        "apply",
        "--production",
        "--manifest",
        manifest.to_str().unwrap(),
        "--stage-dir",
        stage.to_str().unwrap(),
        "--restore-intent",
        restore_intent.to_str().unwrap(),
        "--restore-intent-signature",
        restore_intent_sig.to_str().unwrap(),
        "--operator-verification-key",
        operator_key.to_str().unwrap(),
        "--against",
        anchor_path.to_str().unwrap(),
        "--against-history",
        anchor_history_path.to_str().unwrap(),
        "--anchor-sink",
        "rekor",
        "--sink-path",
        sink_path.to_str().unwrap(),
        "--acknowledge-production-destructive-restore",
        "--acknowledge-active-store-replacement",
    ]);

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("parent of --sink-path"),
        "rekor sink must check parent directory; stderr: {stderr}"
    );
    assert!(
        stderr.contains("active store was not changed"),
        "fail-closed clause must surface; stderr: {stderr}"
    );
    assert!(!sink_path.exists(), "no receipt is written");
}

#[test]
fn production_restore_rekor_sink_rejects_preexisting_sink_path() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let stage = production_apply_stage_dir(tmp.path());
    let restore_intent = dummy_path(tmp.path(), "RESTORE_INTENT.json");
    let restore_intent_sig = dummy_path(tmp.path(), "RESTORE_INTENT.sig");
    let operator_key = dummy_path(tmp.path(), "operator.pubkey");
    let anchor_path = dummy_path(tmp.path(), "ANCHOR.json");
    let anchor_history_path = dummy_path(tmp.path(), "ANCHOR_HISTORY");
    let sink_path = tmp.path().join("preexisting-receipt.json");
    fs::write(&sink_path, b"stale-receipt-bytes").unwrap();

    let out = run(&[
        "restore",
        "apply",
        "--production",
        "--manifest",
        manifest.to_str().unwrap(),
        "--stage-dir",
        stage.to_str().unwrap(),
        "--restore-intent",
        restore_intent.to_str().unwrap(),
        "--restore-intent-signature",
        restore_intent_sig.to_str().unwrap(),
        "--operator-verification-key",
        operator_key.to_str().unwrap(),
        "--against",
        anchor_path.to_str().unwrap(),
        "--against-history",
        anchor_history_path.to_str().unwrap(),
        "--anchor-sink",
        "rekor",
        "--sink-path",
        sink_path.to_str().unwrap(),
        "--acknowledge-production-destructive-restore",
        "--acknowledge-active-store-replacement",
    ]);

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("refusing to overwrite a prior Rekor receipt"),
        "rekor sink must refuse to clobber an existing receipt; stderr: {stderr}"
    );
    // The receipt file must be untouched.
    assert_eq!(fs::read(&sink_path).unwrap(), b"stale-receipt-bytes");
}

#[test]
fn production_restore_rekor_sink_does_not_refuse_at_freshness_gate_for_current_snapshot() {
    // Regression test for Bug J (drill iter #5): the production-restore
    // Rekor sink path used to anchor freshness to the Sigstore tlog
    // signing-key activation date, which made the embedded snapshot
    // *always* stale under the 30-day rule. The fix anchors to
    // EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE (2026-05-12). This test pins
    // the new behaviour: when the embedded snapshot is current, the
    // freshness gate must NOT refuse with
    // `restore.production.sink.rekor.trust_root_snapshot_stale` (nor the
    // back-compat generic `trusted_root_stale`). It does not assert
    // happy-path success — the placeholder RESTORE_INTENT fails the
    // downstream intent verification gate, which is the expected next
    // failure mode.
    //
    // EXPIRES: this test is implicitly time-bound to the embedded
    // snapshot date + 30 days. When the snapshot is refreshed via the
    // build-time embed update, the window slides forward automatically.
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let stage = production_apply_stage_dir(tmp.path());
    let restore_intent = dummy_path(tmp.path(), "RESTORE_INTENT.json");
    let restore_intent_sig = dummy_path(tmp.path(), "RESTORE_INTENT.sig");
    let operator_key = dummy_path(tmp.path(), "operator.pubkey");
    let anchor_path = dummy_path(tmp.path(), "ANCHOR.json");
    let anchor_history_path = dummy_path(tmp.path(), "ANCHOR_HISTORY");
    let receipt_dir = tmp.path().join("evidence");
    fs::create_dir_all(&receipt_dir).unwrap();
    let sink_path = receipt_dir.join("production-restore-rekor-receipt.json");

    let out = run(&[
        "restore",
        "apply",
        "--production",
        "--manifest",
        manifest.to_str().unwrap(),
        "--stage-dir",
        stage.to_str().unwrap(),
        "--restore-intent",
        restore_intent.to_str().unwrap(),
        "--restore-intent-signature",
        restore_intent_sig.to_str().unwrap(),
        "--operator-verification-key",
        operator_key.to_str().unwrap(),
        "--against",
        anchor_path.to_str().unwrap(),
        "--against-history",
        anchor_history_path.to_str().unwrap(),
        "--anchor-sink",
        "rekor",
        "--sink-path",
        sink_path.to_str().unwrap(),
        "--acknowledge-production-destructive-restore",
        "--acknowledge-active-store-replacement",
    ]);

    let stderr = String::from_utf8_lossy(&out.stderr);
    // Specific invariant must not appear (Bug J pin).
    assert!(
        !stderr.contains("restore.production.sink.rekor.trust_root_snapshot_stale"),
        "freshness gate must NOT refuse on current embedded snapshot; stderr: {stderr}"
    );
    // Back-compat generic invariant must not appear either.
    assert!(
        !stderr.contains("restore.production.sink.rekor.trusted_root_stale"),
        "freshness gate must NOT refuse on current embedded snapshot (generic invariant); stderr: {stderr}"
    );
    // No receipt is written because downstream gates fail.
    assert!(
        !sink_path.exists(),
        "no receipt is written without a fully validated drill"
    );
}

#[test]
fn production_restore_rekor_sink_accepts_writable_sink_path() {
    // The sink-kind whitelist accepts `rekor` and the sink-path
    // pre-flight gate accepts a not-yet-existing path with a writable
    // parent directory. We do not drive the full happy path here (that
    // requires a signed RESTORE_INTENT + active store + a fixture Rekor
    // receipt, which is exercised by the restore-drill script).
    // Instead, we assert that the next gate is the RESTORE_INTENT
    // verification, not the sink whitelist.
    let tmp = tempfile::tempdir().unwrap();
    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let stage = production_apply_stage_dir(tmp.path());
    let restore_intent = dummy_path(tmp.path(), "RESTORE_INTENT.json");
    let restore_intent_sig = dummy_path(tmp.path(), "RESTORE_INTENT.sig");
    let operator_key = dummy_path(tmp.path(), "operator.pubkey");
    let anchor_path = dummy_path(tmp.path(), "ANCHOR.json");
    let anchor_history_path = dummy_path(tmp.path(), "ANCHOR_HISTORY");
    let receipt_dir = tmp.path().join("evidence");
    fs::create_dir_all(&receipt_dir).unwrap();
    let sink_path = receipt_dir.join("production-restore-rekor-receipt.json");

    let out = run(&[
        "restore",
        "apply",
        "--production",
        "--manifest",
        manifest.to_str().unwrap(),
        "--stage-dir",
        stage.to_str().unwrap(),
        "--restore-intent",
        restore_intent.to_str().unwrap(),
        "--restore-intent-signature",
        restore_intent_sig.to_str().unwrap(),
        "--operator-verification-key",
        operator_key.to_str().unwrap(),
        "--against",
        anchor_path.to_str().unwrap(),
        "--against-history",
        anchor_history_path.to_str().unwrap(),
        "--anchor-sink",
        "rekor",
        "--sink-path",
        sink_path.to_str().unwrap(),
        "--acknowledge-production-destructive-restore",
        "--acknowledge-active-store-replacement",
    ]);

    // The sink-kind gate is past; the next failure must be downstream
    // (the placeholder staged artifact fails size verification before
    // RESTORE_INTENT verification). Crucially: the sink-kind unknown
    // invariant MUST NOT have fired, and the active store is not
    // changed.
    //
    // Bug J (2026-05-12) fix update: the Rekor freshness gate previously
    // refused here with `Exit::PreconditionUnmet` (7) because it was
    // anchored to the Sigstore tlog signing-key activation date. With
    // the correct anchor (EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE for the
    // embedded path; cache mtime for the cached path), the gate passes
    // on a current snapshot and execution falls through to the staged
    // artifact pre-cutover validation, which fails with
    // `Exit::QuarantinedInput` (5) on the placeholder bytes.
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.contains("restore.production.sink_kind.unknown"),
        "rekor must be accepted by the sink-kind whitelist; stderr: {stderr}"
    );
    assert!(
        !stderr.contains("--anchor-sink must be `external-append-only`"),
        "back-compat regression: rekor must not fall through to the legacy reject; stderr: {stderr}"
    );
    assert!(
        !stderr.contains("restore.production.sink.rekor.trust_root_snapshot_stale")
            && !stderr.contains("restore.production.sink.rekor.trust_root_cache_stale")
            && !stderr.contains("restore.production.sink.rekor.trusted_root_stale"),
        "freshness gate must NOT refuse on current embedded snapshot (Bug J pin); stderr: {stderr}"
    );
    assert_exit(&out, 5);
    assert!(
        !sink_path.exists(),
        "no receipt is written without a fully validated drill"
    );
}

// =============================================================================
// Attack A closure: structural binding of operator_principal_id to verifying key
// =============================================================================
//
// `docs/reviews/RED_TEAM_2026-05-12_post_8f43450.md` Attack A:
// `verify_detached_signature` used to admit ANY 32-byte Ed25519 key for ANY
// claimed `operator_principal_id`. The fix derives the principal id
// deterministically from the key bytes and refuses any payload whose
// `operator_principal_id` does not match that derivation. This integration
// test drives the full CLI all the way to the principal-binding gate and pins
// the stable invariant surface.

fn principal_binding_derive(key_bytes: &[u8; 32]) -> String {
    // Mirrors `derive_operator_principal_id` in
    // `crates/cortex-cli/src/cmd/restore/intent.rs`. Kept duplicated here
    // so the integration test does not depend on the lib internals; if
    // the production derivation ever changes, this test must change
    // alongside it (the assertion will catch divergence).
    //
    // The full 32-byte BLAKE3 digest (64 hex chars) is used, no truncation
    // — see `OPERATOR_PRINCIPAL_FINGERPRINT_HEX_LEN` doc-comment for the
    // rationale (Red Team v2 INFO / Code Review v2 MEDIUM closure).
    let digest = blake3::hash(key_bytes);
    let hex = digest.to_hex().to_string();
    format!("operator:{hex}")
}

fn principal_binding_derive_deployment_id(data_dir: &Path) -> String {
    let canon = data_dir
        .canonicalize()
        .unwrap_or_else(|_| data_dir.to_path_buf());
    let digest = blake3::hash(canon.to_string_lossy().as_bytes());
    format!("deployment:{}", digest.to_hex())
}

#[test]
fn production_restore_refuses_principal_not_bound_to_verifying_key() {
    use ed25519_dalek::{Signer, SigningKey};

    let tmp = tempfile::tempdir().unwrap();

    // Initialize a real cortex active store under a per-test data dir so
    // the verifier's canonical path / deployment-id / digest gates pass
    // and execution reaches the principal-binding check.
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let data_dir = active_db.parent().unwrap().to_path_buf();
    let active_jsonl = data_dir.join("events.jsonl");
    // The init-only store has an empty JSONL; append one fixture event so
    // there is something to audit-verify in the staged copy.
    append_fixture_event(&active_jsonl);

    // Build a backup manifest + staged candidate that mirror the active
    // bytes byte-for-byte (digests must match the payload claims).
    let stage = tmp.path().join("stage");
    fs::create_dir_all(&stage).unwrap();
    let staged_db = stage.join("cortex.db");
    let staged_jsonl = stage.join("events.jsonl");
    fs::copy(&active_db, &staged_db).unwrap();
    fs::copy(&active_jsonl, &staged_jsonl).unwrap();
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &staged_db, &staged_jsonl);

    // Forge: attacker mints a fresh Ed25519 keypair and claims a
    // principal id distinct from the structural derivation.
    let signing_key = SigningKey::from_bytes(&[42u8; 32]);
    let verifying_key = signing_key.verifying_key();
    let key_bytes = verifying_key.to_bytes();
    let derived_principal = principal_binding_derive(&key_bytes);
    let forged_principal = "operator:trusted-incident-responder";
    assert_ne!(
        forged_principal, derived_principal,
        "test premise: forged principal must differ from derived",
    );

    let operator_key_path = tmp.path().join("operator.pubkey");
    fs::write(&operator_key_path, key_bytes).unwrap();

    // Compute deployment id + canonical paths the way the verifier
    // does, so all earlier gates pass.
    let deployment_id = principal_binding_derive_deployment_id(&data_dir);
    let active_db_canon = active_db
        .canonicalize()
        .unwrap_or_else(|_| active_db.clone());
    let active_jsonl_canon = active_jsonl
        .canonicalize()
        .unwrap_or_else(|_| active_jsonl.clone());

    let manifest_bytes = fs::read(&manifest).unwrap();
    let manifest_b3 = blake3_digest(&manifest_bytes);
    let staged_db_b3 = blake3_digest(&fs::read(&staged_db).unwrap());
    let staged_jsonl_b3 = blake3_digest(&fs::read(&staged_jsonl).unwrap());

    let not_before = Utc::now() - chrono::Duration::minutes(5);
    let not_after = Utc::now() + chrono::Duration::hours(1);

    // Mint payload + sign canonical bytes byte-for-byte.
    let payload = json!({
        "kind": "cortex_restore_intent",
        "schema_version": 1,
        "deployment_id": deployment_id,
        "active_db_path": active_db_canon,
        "active_event_log_path": active_jsonl_canon,
        "backup_manifest_blake3": manifest_b3,
        "staged_sqlite_blake3": staged_db_b3,
        "staged_jsonl_blake3": staged_jsonl_b3,
        "operator_principal_id": forged_principal,
        "not_before": not_before.to_rfc3339(),
        "not_after": not_after.to_rfc3339(),
        "p_n_schema_version": 1,
    });
    let canonical_bytes = serde_json::to_vec(&payload).unwrap();
    let restore_intent = tmp.path().join("RESTORE_INTENT.json");
    fs::write(&restore_intent, &canonical_bytes).unwrap();
    let signature = signing_key.sign(&canonical_bytes);
    let restore_intent_sig = tmp.path().join("RESTORE_INTENT.sig");
    fs::write(&restore_intent_sig, signature.to_bytes()).unwrap();

    let anchor_path = dummy_path(tmp.path(), "ANCHOR.json");
    let anchor_history_path = dummy_path(tmp.path(), "ANCHOR_HISTORY");
    // Council Q1 (2026-05-12) refused `--anchor-sink external-append-only`
    // at the parser (Finding F1), so this test routes through the
    // authorized `--anchor-sink rekor` path to reach the
    // principal-binding gate. The rekor sink-path must not already
    // exist (atomic file write, no clobber) and must live under an
    // existing parent directory.
    let sink_path = tmp.path().join("production-restore-rekor-receipt.json");
    assert!(
        !sink_path.exists(),
        "test premise: sink_path must not exist for rekor cutover gate"
    );

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "apply",
            "--production",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage.to_str().unwrap(),
            "--restore-intent",
            restore_intent.to_str().unwrap(),
            "--restore-intent-signature",
            restore_intent_sig.to_str().unwrap(),
            "--operator-verification-key",
            operator_key_path.to_str().unwrap(),
            "--against",
            anchor_path.to_str().unwrap(),
            "--against-history",
            anchor_history_path.to_str().unwrap(),
            "--anchor-sink",
            "rekor",
            "--sink-path",
            sink_path.to_str().unwrap(),
            "--acknowledge-production-destructive-restore",
            "--acknowledge-active-store-replacement",
        ],
    );

    // Process must exit non-zero (the verifier maps the binding
    // failure to Exit::QuarantinedInput == 5).
    let code = out.status.code().expect("process exited via signal");
    assert_ne!(
        code,
        0,
        "principal-binding fail-closed gate must refuse; stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("restore.intent.operator_principal_id.not_bound_to_verifying_key"),
        "stable invariant must surface in stderr; stderr: {stderr}",
    );
    assert!(
        stderr.contains("active store was not changed"),
        "fail-closed clause must surface; stderr: {stderr}",
    );
    // The rekor sink path is the destination for the Rekor receipt
    // JSON; it is written ONLY on the full-success path. The
    // principal-binding fail-closed gate must refuse before any
    // witness emission, so no receipt may be on disk after the run.
    assert!(
        !sink_path.exists(),
        "principal-binding fail-closed must not write a rekor receipt",
    );
}

// =============================================================================
// Phase 2.6 — restore recover-apply / restore apply --production refusal tests
//
// `docs/design/PHASE_2_6_temporal_authority_revalidation_audit.md` §T1:
// recover-apply and production restore MUST consult the durable
// `authority_key_timeline` for the operator-supplied key before letting
// the destructive cutover proceed. A revoked-after-signing or absent
// key votes `Reject` and the surface refuses with
// `restore.recover_apply.operator_temporal_authority.revalidation_failed`
// or
// `restore.production.operator_temporal_authority.revalidation_failed`.
// =============================================================================

#[test]
fn restore_recover_apply_refuses_when_operator_attestation_missing() {
    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);
    let apply = run_in(
        tmp.path(),
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--acknowledge-active-store-replacement",
            "--acknowledge-temp-test-data-dir",
        ],
    );
    assert_exit(&apply, 0);
    let apply_report: serde_json::Value = serde_json::from_slice(&apply.stdout).unwrap();
    let recovery_manifest = PathBuf::from(
        apply_report["recovery_evidence"]["manifest"]
            .as_str()
            .unwrap(),
    );

    // Run recover-apply WITHOUT --attestation. Phase 2.6 requires durable
    // timeline revalidation; absent attestation must fail closed with the
    // stable invariant.
    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "recover-apply",
            "--manifest",
            recovery_manifest.to_str().unwrap(),
            "--acknowledge-current-backup-restore",
            "--acknowledge-temp-test-data-dir",
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("restore.recover_apply.operator_temporal_authority.revalidation_failed")
            && stderr.contains("--attestation <PATH> is required"),
        "stderr must carry the stable invariant + remediation hint: {stderr}"
    );
}

#[test]
fn restore_recover_apply_refuses_when_operator_key_revoked() {
    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);
    let apply = run_in(
        tmp.path(),
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--acknowledge-active-store-replacement",
            "--acknowledge-temp-test-data-dir",
        ],
    );
    assert_exit(&apply, 0);
    let apply_report: serde_json::Value = serde_json::from_slice(&apply.stdout).unwrap();
    let recovery_manifest = PathBuf::from(
        apply_report["recovery_evidence"]["manifest"]
            .as_str()
            .unwrap(),
    );

    // Seed the operator-key timeline, then revoke the key. recover-apply
    // signs at `now`, so `event_time = now >= revoked_at` -> `Reject`.
    let (attestation_key, attestor) = restore_attestation_key_fixture(tmp.path());
    seed_operator_authority_for_restore(&active_db, &attestor);
    revoke_operator_authority_for_restore(
        &active_db,
        &attestor,
        Utc.with_ymd_and_hms(2026, 1, 1, 12, 0, 2).unwrap(),
    );

    let out = run_in(
        tmp.path(),
        &[
            "restore",
            "recover-apply",
            "--manifest",
            recovery_manifest.to_str().unwrap(),
            "--acknowledge-current-backup-restore",
            "--acknowledge-temp-test-data-dir",
            "--attestation",
            attestation_key.to_str().unwrap(),
        ],
    );

    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("restore.recover_apply.operator_temporal_authority.revalidation_failed"),
        "stderr must carry the stable invariant: {stderr}"
    );
    // The revoked-after-signing reason should surface for operator
    // diagnostics.
    assert!(
        stderr.contains("signed_after_revocation") || stderr.contains("revoked_after_signing"),
        "stderr should name the per-reason wire string: {stderr}"
    );
}

// =============================================================================
// Attack E closure
// (`docs/reviews/CODE_REVIEW_2026-05-12_post_fd779d7.md`):
// the production destructive restore path must refuse the test-only
// `CORTEX_REKOR_FIXTURE_RECEIPT` env var BEFORE any active-store
// mutation, intent verification, lock acquisition, or sink-kind
// dispatch. The fixture-receipt override was authored for the
// non-`--production` apply-stage path and intentionally does not
// re-bind the receipt's anchor to the active JSONL — honoring it on
// production would defeat the disjoint-authority gate that F1 closure
// (Rekor mandatory) was supposed to enforce.
// =============================================================================

/// Run the CLI with `CORTEX_REKOR_FIXTURE_RECEIPT` set to an arbitrary
/// (non-empty) path. The fixture file does not have to exist for the
/// production-path refusal to fire — the refusal is on the env var
/// presence, not on the file at the path.
fn run_with_fixture_env(cwd: &Path, fixture_path: &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"))
        .env("CORTEX_REKOR_FIXTURE_RECEIPT", fixture_path)
        .args(args)
        .output()
        .expect("spawn cortex")
}

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

    // Establish a real active store so we can assert the refusal
    // happens BEFORE any cutover bytes touch it.
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let active_jsonl = active_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&active_jsonl);
    let active_db_bytes_before = fs::read(&active_db).unwrap();
    let active_jsonl_bytes_before = fs::read(&active_jsonl).unwrap();

    let manifest = write_pre_v2_backup(&tmp.path().join("backup"));
    let stage = production_apply_stage_dir(tmp.path());
    let restore_intent = dummy_path(tmp.path(), "RESTORE_INTENT.json");
    let restore_intent_sig = dummy_path(tmp.path(), "RESTORE_INTENT.sig");
    let operator_key = dummy_path(tmp.path(), "operator.pubkey");
    let anchor_path = dummy_path(tmp.path(), "ANCHOR.json");
    let anchor_history_path = dummy_path(tmp.path(), "ANCHOR_HISTORY");
    let sink_path = tmp.path().join("sink");

    // Path does not have to exist; the refusal fires on env var
    // presence at the production entry-point.
    let fixture_receipt = tmp.path().join("rekor-fixture-receipt.txt");

    let out = run_with_fixture_env(
        tmp.path(),
        &fixture_receipt,
        &[
            "restore",
            "apply",
            "--production",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage.to_str().unwrap(),
            "--restore-intent",
            restore_intent.to_str().unwrap(),
            "--restore-intent-signature",
            restore_intent_sig.to_str().unwrap(),
            "--operator-verification-key",
            operator_key.to_str().unwrap(),
            "--against",
            anchor_path.to_str().unwrap(),
            "--against-history",
            anchor_history_path.to_str().unwrap(),
            "--anchor-sink",
            "rekor",
            "--sink-path",
            sink_path.to_str().unwrap(),
            "--acknowledge-production-destructive-restore",
            "--acknowledge-active-store-replacement",
        ],
    );

    // Exit::PreconditionUnmet == 7. Refusal must fire before mutation.
    assert_exit(&out, 7);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("restore.production.rekor_fixture_receipt_env_forbidden_in_production"),
        "stable invariant must surface; stderr: {stderr}"
    );
    assert!(
        stderr.contains("active store was not changed"),
        "fail-closed clause must surface; stderr: {stderr}"
    );
    // No cutover artifacts may have been written.
    assert_eq!(fs::read(&active_db).unwrap(), active_db_bytes_before);
    assert_eq!(fs::read(&active_jsonl).unwrap(), active_jsonl_bytes_before);
    assert!(!sink_path.exists(), "no sink artifact may be written");
}

#[test]
fn apply_stage_still_honors_rekor_fixture_receipt_env_on_temp_test_path() {
    // The fixture-receipt path is test-only on the non-`--production`
    // apply-stage path. The Attack E refusal must NOT regress that
    // surface — temp-test integration tests legitimately use the env
    // var to inject deterministic receipts. We verify this by setting
    // the env var and running a clean apply-stage; the temp-test path
    // does not even reach the Rekor sink (no `--anchor-sink rekor` is
    // accepted on apply-stage), so the env var must be a no-op there.
    let tmp = tempfile::tempdir().unwrap();
    let active_db = init_store(tmp.path());
    apply_store_migrations(&active_db);
    let candidate_root = tmp.path().join("candidate");
    fs::create_dir_all(&candidate_root).unwrap();
    let candidate_db = init_store(&candidate_root);
    apply_store_migrations(&candidate_db);
    let candidate_log = candidate_db.parent().unwrap().join("events.jsonl");
    append_fixture_event(&candidate_log);
    let manifest =
        write_manifest_for_artifacts(&tmp.path().join("backup"), &candidate_db, &candidate_log);
    let stage_dir = tmp.path().join("stage");
    let stage = run_in(
        tmp.path(),
        &[
            "restore",
            "stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--current-store",
            active_db.to_str().unwrap(),
            "--acknowledge-destructive-restore",
        ],
    );
    assert_exit(&stage, 0);

    let fixture_receipt = tmp.path().join("rekor-fixture-receipt.txt");
    fs::write(&fixture_receipt, b"placeholder-fixture-receipt").unwrap();

    let apply = run_with_fixture_env(
        tmp.path(),
        &fixture_receipt,
        &[
            "restore",
            "apply-stage",
            "--manifest",
            manifest.to_str().unwrap(),
            "--stage-dir",
            stage_dir.to_str().unwrap(),
            "--acknowledge-active-store-replacement",
            "--acknowledge-temp-test-data-dir",
        ],
    );
    // apply-stage on temp-test does not engage the Rekor sink at all;
    // the env var must not block this path. The exit code MUST NOT be
    // 7 with the fixture-env-forbidden invariant.
    let stderr = String::from_utf8_lossy(&apply.stderr);
    assert!(
        !stderr.contains("rekor_fixture_receipt_env_forbidden_in_production"),
        "apply-stage temp-test path must not surface the production-only refusal: stderr={stderr}"
    );
}