crtx 0.1.1

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

pub mod intent;
pub mod intent_build;
pub mod lock;
pub mod policy;
pub mod production;

use std::fs::{self, File, OpenOptions};
use std::io::{ErrorKind, Read, Write};
use std::path::{Path, PathBuf};

use clap::{Args, Subcommand};
use cortex_core::{
    effective_ceiling, AuditRecordId, AuthorityClass, ClaimCeiling, ClaimProofState, RuntimeMode,
};
use cortex_ledger::{
    anchor::{verify_anchor_history, AnchorHistoryVerifyError},
    audit::verify_chain,
    parse_anchor, verify_anchor, AnchorVerifyError, JsonlError, Report,
};
use cortex_store::repo::{AuditEntry, AuditRepo};
use cortex_store::semantic_diff::{
    semantic_snapshot_from_store, RestoreDecision, SemanticSnapshot,
};
use serde::Deserialize;
use serde_json::json;

/// Render the ADR 0037 §5 truth-ceiling triad as a JSON object for a
/// restore-side surface. Restore operations run entirely under
/// `local_unsigned` runtime mode: the bundle / manifest / staged
/// candidate is local evidence, not signed-ledger or external-anchor
/// output, regardless of the cutover semantics. `proof_state` follows
/// the most recent observed verification result (or `unknown` when no
/// verification has run yet), `authority_class` reflects whether the
/// operator authorised the restore through a verified intent envelope
/// (`verified`) or only acknowledged risk flags on a temp-test path
/// (`observed`), and `claim_ceiling` clamps to the weakest signal.
fn restore_truth_ceiling_object(
    proof_state: ClaimProofState,
    authority_class: AuthorityClass,
) -> serde_json::Value {
    let runtime_mode = RuntimeMode::LocalUnsigned;
    let claim_ceiling = effective_ceiling(
        runtime_mode,
        authority_class,
        proof_state,
        ClaimCeiling::LocalUnsigned,
    );
    json!({
        "runtime_mode": runtime_mode,
        "proof_state": proof_state,
        "claim_ceiling": claim_ceiling,
        "authority_class": authority_class,
    })
}

/// Fail-closed default truth ceiling for a restore surface that has
/// not observed any verification yet. The §5 amendment requires every
/// new restore envelope to carry the typed triad even when the
/// producer has not yet computed a stronger value — this is the
/// minimum.
fn restore_truth_ceiling_fail_closed() -> serde_json::Value {
    restore_truth_ceiling_object(ClaimProofState::Unknown, AuthorityClass::Observed)
}

use crate::cmd::open_default_store;
use crate::cmd::temporal::{revalidate_operator_temporal_authority, revalidation_failed_invariant};
use crate::exit::Exit;
use crate::paths::DataLayout;
use cortex_core::{Attestor, InMemoryAttestor, TrustTier};

const APPLY_RECOVERY_DIR_NAME: &str = ".restore-apply-recovery";
const APPLY_RECOVERY_MANIFEST_NAME: &str = "RECOVERY_MANIFEST.json";
const RESTORE_APPLY_STAGE_COMMAND_AUDIT_OPERATION: &str = "command.restore.apply_stage";
const RESTORE_RECOVER_APPLY_COMMAND_AUDIT_OPERATION: &str = "command.restore.recover_apply";

/// Restore validation subcommands.
#[derive(Debug, Subcommand)]
pub enum RestoreSub {
    /// Extract the current semantic snapshot from the local store.
    Snapshot(SnapshotArgs),
    /// Compare current and candidate restore semantic snapshots.
    SemanticDiff(SemanticDiffArgs),
    /// Verify a backup manifest and its listed artifacts without restoring.
    VerifyBackup(VerifyBackupArgs),
    /// Verify the tamper-evident BLAKE3 digest on a post-migrate manifest
    /// produced by `cortex migrate v2` (Decision #6 / RED_TEAM_FINDINGS D2).
    VerifyPostMigrateManifest(VerifyPostMigrateManifestArgs),
    /// Run read-only structural and semantic restore preflight checks.
    Preflight(PreflightArgs),
    /// Stage a restore candidate behind destructive-restore guards.
    Stage(StageArgs),
    /// RESTORE_INTENT payload helpers (mint canonical bytes; optionally sign).
    Intent {
        /// Intent operation to run.
        #[command(subcommand)]
        sub: IntentSub,
    },
    /// Apply a verified staged restore candidate to the active store.
    /// `--production` switches to the destructive production path; otherwise
    /// the temp-test apply remains the only mutation route. Boxed so the
    /// surrounding enum stays compact (`clippy::large_enum_variant`).
    Apply(Box<production::ApplyArgs>),
    /// Apply a verified staged restore candidate to a temp-test active store.
    ApplyStage(ApplyStageArgs),
    /// Restore current backups from an apply-stage recovery manifest.
    RecoverApply(RecoverApplyArgs),
}

/// `cortex restore intent ...` sub-dispatcher. Currently exposes the `build`
/// minter; future helpers (verify, inspect) will land here too so the
/// `RESTORE_INTENT` lifecycle has one named subtree on the CLI.
#[derive(Debug, Subcommand)]
pub enum IntentSub {
    /// Mint a `RESTORE_INTENT` JSON payload and optionally sign it.
    Build(intent_build::BuildArgs),
}

/// `cortex restore snapshot` flags.
#[derive(Debug, Args)]
pub struct SnapshotArgs {
    /// Existing candidate SQLite store to inspect read-only instead of the default store.
    #[arg(long)]
    pub store: Option<PathBuf>,
}

/// `cortex restore semantic-diff` flags.
#[derive(Debug, Args)]
pub struct SemanticDiffArgs {
    /// Current accepted semantic snapshot JSON.
    #[arg(long)]
    pub current: Option<PathBuf>,
    /// Candidate restored semantic snapshot JSON.
    #[arg(long)]
    pub restored: Option<PathBuf>,
    /// Current accepted SQLite store to inspect read-only.
    #[arg(long)]
    pub current_store: Option<PathBuf>,
    /// Candidate restored SQLite store to inspect read-only.
    #[arg(long)]
    pub restored_store: Option<PathBuf>,
    /// Acknowledge recovery risk for blocked semantic drift.
    #[arg(long)]
    pub acknowledge_recovery_risk: bool,
}

/// `cortex restore verify-backup` flags.
#[derive(Debug, Args)]
pub struct VerifyBackupArgs {
    /// Backup manifest to verify.
    #[arg(long, value_name = "PATH")]
    pub manifest: PathBuf,
}

/// `cortex restore verify-post-migrate-manifest` flags.
///
/// Verifies the tamper-evident BLAKE3 digest on a `POST_V2_MIGRATE_MANIFEST`
/// emitted by `cortex migrate v2` (Decision #6 / RED_TEAM_FINDINGS D2). The
/// digest is computed over the canonical-serialized manifest body excluding
/// the `manifest_blake3` field itself; a mismatch fails closed.
#[derive(Debug, Args)]
pub struct VerifyPostMigrateManifestArgs {
    /// Path to the `POST_V2_MIGRATE_MANIFEST` JSON file to verify.
    #[arg(long, value_name = "PATH")]
    pub manifest: PathBuf,
}

/// `cortex restore preflight` flags.
#[derive(Debug, Args)]
pub struct PreflightArgs {
    /// Backup manifest to verify before any semantic check.
    #[arg(long, value_name = "PATH")]
    pub manifest: PathBuf,
    /// Current accepted SQLite store to inspect read-only.
    #[arg(long)]
    pub current_store: Option<PathBuf>,
    /// Candidate restored SQLite store to inspect read-only.
    #[arg(long)]
    pub candidate_store: Option<PathBuf>,
    /// Acknowledge recovery risk for blocked semantic drift.
    #[arg(long)]
    pub acknowledge_recovery_risk: bool,
    /// Emit a fail-closed production active-store restore plan without mutating state.
    #[arg(long)]
    pub production_active_store_plan: bool,
    /// Existing active-store lock marker to inspect for production restore planning.
    #[arg(long, value_name = "PATH")]
    pub active_store_lock_marker: Option<PathBuf>,
}

/// `cortex restore stage` flags.
#[derive(Debug, Args)]
pub struct StageArgs {
    /// Backup manifest to verify before staging.
    #[arg(long, value_name = "PATH")]
    pub manifest: PathBuf,
    /// Non-existent directory where the verified restore candidate will be staged.
    #[arg(long, value_name = "DIR")]
    pub stage_dir: PathBuf,
    /// Current accepted SQLite store to inspect read-only.
    #[arg(long)]
    pub current_store: Option<PathBuf>,
    /// Acknowledge that this staged candidate is intended for destructive restore review.
    #[arg(long)]
    pub acknowledge_destructive_restore: bool,
    /// Acknowledge recovery risk for blocked semantic drift.
    #[arg(long)]
    pub acknowledge_recovery_risk: bool,
}

/// `cortex restore apply-stage` flags.
#[derive(Debug, Args)]
pub struct ApplyStageArgs {
    /// Backup manifest that originally authorized the staged candidate.
    #[arg(long, value_name = "PATH")]
    pub manifest: PathBuf,
    /// Existing staged candidate directory containing cortex.db and events.jsonl.
    #[arg(long, value_name = "DIR")]
    pub stage_dir: PathBuf,
    /// Acknowledge that the active temp-test store will be replaced.
    #[arg(long)]
    pub acknowledge_active_store_replacement: bool,
    /// Acknowledge this command is limited to a temp-test data directory.
    #[arg(long)]
    pub acknowledge_temp_test_data_dir: bool,
    /// Acknowledge recovery risk for blocked semantic drift.
    #[arg(long)]
    pub acknowledge_recovery_risk: bool,
    /// Optional position-bound anchor to verify against the restored active JSONL after cutover.
    #[arg(long = "post-restore-anchor", value_name = "ANCHOR_PATH")]
    pub post_restore_anchor: Option<PathBuf>,
    /// Optional monotonic anchor history to verify against the restored active JSONL after cutover.
    #[arg(
        long = "post-restore-anchor-history",
        value_name = "ANCHOR_HISTORY_PATH"
    )]
    pub post_restore_anchor_history: Option<PathBuf>,
}

/// `cortex restore recover-apply` flags.
#[derive(Debug, Args)]
pub struct RecoverApplyArgs {
    /// Apply-stage recovery manifest produced before active replacement.
    #[arg(long, value_name = "PATH")]
    pub manifest: PathBuf,
    /// Acknowledge that active temp-test files will be restored from current backups.
    #[arg(long)]
    pub acknowledge_current_backup_restore: bool,
    /// Acknowledge this command is limited to a temp-test data directory.
    #[arg(long)]
    pub acknowledge_temp_test_data_dir: bool,
    /// Path to a raw 32-byte Ed25519 seed file proving operator authority
    /// for this recover-apply. Phase 2.6 closure
    /// (`docs/design/PHASE_2_6_temporal_authority_revalidation_audit.md`)
    /// requires durable timeline revalidation of the bound operator key
    /// at `minimum_trust_tier = Operator` before the destructive recover.
    /// Absent attestation refuses with the stable invariant
    /// `restore.recover_apply.operator_temporal_authority.revalidation_failed`.
    #[arg(long, value_name = "KEY_PATH")]
    pub attestation: Option<PathBuf>,
}

#[derive(Debug, Deserialize)]
struct PreV2BackupManifest {
    kind: String,
    schema_version: u16,
    sqlite_store: String,
    jsonl_mirror: String,
    tool_version: String,
    backup_timestamp: String,
    sqlite_store_size_bytes: u64,
    sqlite_store_blake3: String,
    jsonl_mirror_size_bytes: u64,
    jsonl_mirror_blake3: String,
}

#[derive(Debug)]
struct VerifiedBackup {
    schema_version: u16,
    sqlite_store: VerifiedArtifact,
    jsonl_mirror: VerifiedArtifact,
}

#[derive(Debug)]
struct VerifiedArtifact {
    manifest_field: &'static str,
    path: PathBuf,
    size_bytes: u64,
    blake3: String,
}

#[derive(Debug)]
pub(super) struct ApplyRecoveryEvidence {
    pub(super) manifest_path: PathBuf,
    pub(super) active_db_backup: PathBuf,
    pub(super) active_event_log_backup: PathBuf,
    /// BLAKE3 of the pre-cutover SQLite backup as recorded in the recovery
    /// manifest. Used by [`restore_current_backups`] to re-verify the file
    /// after `fs::copy` so a tampered backup cannot land via the rollback
    /// path (Attack C closure — Rekor failure is now the common rollback
    /// trigger since Rekor is mandatory).
    pub(super) active_db_backup_blake3: String,
    /// BLAKE3 of the pre-cutover JSONL backup as recorded in the recovery
    /// manifest. Same re-verify contract as `active_db_backup_blake3`.
    pub(super) active_event_log_backup_blake3: String,
}

#[derive(Debug, Deserialize)]
struct ApplyRecoveryManifest {
    kind: String,
    schema_version: u16,
    scope: String,
    status: String,
    active: ApplyRecoveryPaths,
    active_backups: ApplyRecoveryBackups,
}

#[derive(Debug, Deserialize)]
struct ApplyRecoveryPaths {
    db: PathBuf,
    event_log: PathBuf,
}

#[derive(Debug, Deserialize)]
struct ApplyRecoveryBackups {
    db: ApplyRecoveryBackupArtifact,
    event_log: ApplyRecoveryBackupArtifact,
}

#[derive(Debug, Deserialize)]
struct ApplyRecoveryBackupArtifact {
    path: PathBuf,
    size_bytes: u64,
    blake3: String,
}

/// Run a restore validation command.
pub fn run(sub: RestoreSub) -> Exit {
    match sub {
        RestoreSub::Snapshot(args) => run_snapshot(args),
        RestoreSub::SemanticDiff(args) => run_semantic_diff(args),
        RestoreSub::VerifyBackup(args) => run_verify_backup(args),
        RestoreSub::VerifyPostMigrateManifest(args) => run_verify_post_migrate_manifest(args),
        RestoreSub::Preflight(args) => run_preflight(args),
        RestoreSub::Stage(args) => run_stage(args),
        RestoreSub::Intent { sub } => match sub {
            IntentSub::Build(args) => intent_build::run(args),
        },
        RestoreSub::Apply(args) => production::run_apply(*args),
        RestoreSub::ApplyStage(args) => run_apply_stage(args),
        RestoreSub::RecoverApply(args) => run_recover_apply(args),
    }
}

fn run_snapshot(args: SnapshotArgs) -> Exit {
    let pool = match args.store {
        Some(path) => match open_readonly_store(&path, "restore snapshot") {
            Ok(pool) => pool,
            Err(exit) => return exit,
        },
        None => match open_default_store("restore snapshot") {
            Ok(pool) => pool,
            Err(exit) => return exit,
        },
    };
    let snapshot = match semantic_snapshot_from_store(&pool) {
        Ok(snapshot) => snapshot,
        Err(err) => {
            eprintln!("cortex restore snapshot: failed to extract semantic snapshot: {err}");
            return Exit::PreconditionUnmet;
        }
    };
    match serde_json::to_string_pretty(&snapshot) {
        Ok(output) => {
            println!("{output}");
            Exit::Ok
        }
        Err(err) => {
            eprintln!("cortex restore snapshot: failed to serialize snapshot: {err}");
            Exit::Internal
        }
    }
}

fn open_readonly_store(path: &Path, command: &str) -> Result<cortex_store::Pool, Exit> {
    if !path.exists() {
        eprintln!(
            "cortex {command}: precondition unmet: store {} does not exist; no state was changed.",
            path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }

    let pool = cortex_store::open_existing_readonly(path).map_err(|err| {
        eprintln!(
            "cortex {command}: failed to open read-only store {}: {err}",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    let report = cortex_store::verify::verify_schema_version(&pool, cortex_core::SCHEMA_VERSION)
        .map_err(|err| {
            eprintln!("cortex {command}: failed to verify schema preconditions: {err}");
            Exit::PreconditionUnmet
        })?;
    if !report.is_ok() {
        for failure in &report.failures {
            eprintln!(
                "cortex {command}: {}: {}",
                failure.invariant(),
                failure.detail()
            );
        }
        return Err(Exit::SchemaMismatch);
    }
    Ok(pool)
}

fn run_semantic_diff(args: SemanticDiffArgs) -> Exit {
    let current = match read_semantic_snapshot_source(
        args.current.as_deref(),
        args.current_store.as_deref(),
        "current",
    ) {
        Ok(snapshot) => snapshot,
        Err(exit) => return exit,
    };
    let restored = match read_semantic_snapshot_source(
        args.restored.as_deref(),
        args.restored_store.as_deref(),
        "restored",
    ) {
        Ok(snapshot) => snapshot,
        Err(exit) => return exit,
    };

    let diff = current.diff_against_restore(&restored);
    // ADR 0026 #23: compose three-contributor `PolicyDecision` for the
    // semantic-diff surface. The legacy `RestoreDecision` shape stays in
    // the JSON report so consumers can transition off it gradually.
    let composed = policy::compose_semantic_diff_decision(
        &diff,
        args.acknowledge_recovery_risk,
        "restore.semantic_diff",
        "snapshot:current_vs_restored",
    );
    let decision = composed.legacy;
    // ADR 0037 §5: semantic-diff compares two stores read-only. The
    // diff itself does not run a hash-chain audit, so `proof_state`
    // stays `unknown` (the producer-side `semantic_snapshot_from_store`
    // currently emits `TruthCeilingState::default()` — see audit D10).
    let truth_ceiling = restore_truth_ceiling_fail_closed();
    let report = json!({
        "command": "restore.semantic_diff",
        "current_snapshot_id": diff.current_snapshot_id,
        "restored_snapshot_id": diff.restored_snapshot_id,
        "severity": diff.severity(),
        "decision": decision,
        "policy_decision": policy::policy_decision_report(&composed.decision),
        "change_count": diff.changes.len(),
        "changes": diff.changes,
        "mutated_store": false,
        "truth_ceiling": truth_ceiling,
    });

    match serde_json::to_string_pretty(&report) {
        Ok(output) => println!("{output}"),
        Err(err) => {
            eprintln!("cortex restore semantic-diff: failed to serialize report: {err}");
            return Exit::Internal;
        }
    }

    match decision {
        RestoreDecision::Clean | RestoreDecision::Warning { .. } => Exit::Ok,
        RestoreDecision::PreconditionUnmet { .. } => Exit::PreconditionUnmet,
    }
}

/// Stable invariant emitted when the post-migrate manifest's `manifest_blake3`
/// field is missing (Decision #6 / RED_TEAM_FINDINGS D2).
///
/// Fail-closed: a manifest without the digest field cannot be verified, so
/// it is refused outright rather than treated as legacy / unverified.
const POST_MIGRATE_MANIFEST_MISSING_DIGEST_INVARIANT: &str =
    "restore.post_migrate_manifest.missing_digest_field";

/// Stable invariant emitted when the post-migrate manifest's recomputed
/// BLAKE3 digest does not match the value embedded in the manifest
/// (Decision #6 / RED_TEAM_FINDINGS D2).
const POST_MIGRATE_MANIFEST_DIGEST_MISMATCH_INVARIANT: &str =
    "restore.post_migrate_manifest.digest_mismatch";

/// Stable invariant emitted when the manifest path argument cannot be read
/// or the JSON does not parse as an object.
const POST_MIGRATE_MANIFEST_UNREADABLE_INVARIANT: &str = "restore.post_migrate_manifest.unreadable";

/// Stable invariant emitted when an auto-rollback restores a pre-cutover
/// backup onto the active store and the freshly-copied file's BLAKE3 does
/// not match the digest recorded in the recovery manifest (Attack C in
/// `docs/reviews/CODE_REVIEW_2026-05-12_post_fd779d7.md`).
///
/// Since F1 (commit `0df500c`) made Rekor mandatory, Rekor failure is the
/// COMMON rollback trigger; a malicious file on the backup path could
/// otherwise land via the rollback `fs::copy` without any digest check.
/// Refuse with [`Exit::IntegrityFailure`] when this invariant fires.
pub const RESTORE_RECOVER_ROLLBACK_BACKUP_DIGEST_MISMATCH_INVARIANT: &str =
    "restore.recover.rollback.backup_digest_mismatch";

/// Phase 4 envelope command name for the verifier.
const VERIFY_POST_MIGRATE_MANIFEST_COMMAND: &str = "cortex.restore.verify_post_migrate_manifest";

/// Manifest-digest field name. Mirrors the producer side
/// (`POST_MIGRATE_MANIFEST_DIGEST_FIELD` in `cmd::migrate`).
const POST_MIGRATE_MANIFEST_DIGEST_FIELD: &str = "manifest_blake3";

fn run_verify_post_migrate_manifest(args: VerifyPostMigrateManifestArgs) -> Exit {
    let raw = match fs::read_to_string(&args.manifest) {
        Ok(raw) => raw,
        Err(err) => {
            eprintln!(
                "cortex restore verify-post-migrate-manifest: {POST_MIGRATE_MANIFEST_UNREADABLE_INVARIANT}: failed to read manifest `{}`: {err}. no state was changed.",
                args.manifest.display()
            );
            return emit_verify_post_migrate_manifest_envelope(
                &args.manifest,
                None,
                None,
                Some(POST_MIGRATE_MANIFEST_UNREADABLE_INVARIANT),
                Exit::PreconditionUnmet,
            );
        }
    };
    let parsed: serde_json::Value = match serde_json::from_str(&raw) {
        Ok(value) => value,
        Err(err) => {
            eprintln!(
                "cortex restore verify-post-migrate-manifest: {POST_MIGRATE_MANIFEST_UNREADABLE_INVARIANT}: manifest `{}` is not valid JSON: {err}. no state was changed.",
                args.manifest.display()
            );
            return emit_verify_post_migrate_manifest_envelope(
                &args.manifest,
                None,
                None,
                Some(POST_MIGRATE_MANIFEST_UNREADABLE_INVARIANT),
                Exit::PreconditionUnmet,
            );
        }
    };
    let serde_json::Value::Object(mut object) = parsed else {
        eprintln!(
            "cortex restore verify-post-migrate-manifest: {POST_MIGRATE_MANIFEST_UNREADABLE_INVARIANT}: manifest `{}` is not a JSON object. no state was changed.",
            args.manifest.display()
        );
        return emit_verify_post_migrate_manifest_envelope(
            &args.manifest,
            None,
            None,
            Some(POST_MIGRATE_MANIFEST_UNREADABLE_INVARIANT),
            Exit::PreconditionUnmet,
        );
    };

    // Split out the digest field. The remaining object is canonicalised and
    // hashed; if the digest field is absent the manifest pre-dates the
    // tamper-evident slice (or has been tampered with by deletion) and we
    // refuse fail-closed per Decision #6.
    let recorded_digest = match object.remove(POST_MIGRATE_MANIFEST_DIGEST_FIELD) {
        Some(serde_json::Value::String(value)) => value,
        Some(_) | None => {
            eprintln!(
                "cortex restore verify-post-migrate-manifest: {POST_MIGRATE_MANIFEST_MISSING_DIGEST_INVARIANT}: manifest `{}` is missing required `{POST_MIGRATE_MANIFEST_DIGEST_FIELD}` field (or it is not a string). Pre-Decision-#6 manifests are not verifiable; refusing fail-closed. no state was changed.",
                args.manifest.display()
            );
            return emit_verify_post_migrate_manifest_envelope(
                &args.manifest,
                None,
                None,
                Some(POST_MIGRATE_MANIFEST_MISSING_DIGEST_INVARIANT),
                Exit::IntegrityFailure,
            );
        }
    };

    let body_without_digest = serde_json::Value::Object(object);
    let recomputed_digest = canonical_blake3_hex(&body_without_digest);
    if recomputed_digest != recorded_digest {
        eprintln!(
            "cortex restore verify-post-migrate-manifest: {POST_MIGRATE_MANIFEST_DIGEST_MISMATCH_INVARIANT}: manifest `{}` BLAKE3 digest mismatch (recorded={}, recomputed={}). Refusing fail-closed; the manifest body was modified after the cutover. no state was changed.",
            args.manifest.display(),
            recorded_digest,
            recomputed_digest
        );
        return emit_verify_post_migrate_manifest_envelope(
            &args.manifest,
            Some(&recorded_digest),
            Some(&recomputed_digest),
            Some(POST_MIGRATE_MANIFEST_DIGEST_MISMATCH_INVARIANT),
            Exit::IntegrityFailure,
        );
    }

    eprintln!(
        "cortex restore verify-post-migrate-manifest: manifest `{}` BLAKE3 digest verified ({}).",
        args.manifest.display(),
        recorded_digest
    );
    emit_verify_post_migrate_manifest_envelope(
        &args.manifest,
        Some(&recorded_digest),
        Some(&recomputed_digest),
        None,
        Exit::Ok,
    )
}

/// Compute the canonical-bytes BLAKE3 digest of a JSON value as
/// `blake3:<hex>`. Mirrors the producer side (`cmd::migrate::canonical_blake3_hex`)
/// so the two paths are byte-stable across re-serialization.
fn canonical_blake3_hex(value: &serde_json::Value) -> String {
    let bytes = cortex_ledger::canonical_payload_bytes(value);
    format!("blake3:{}", blake3::hash(&bytes).to_hex())
}

fn emit_verify_post_migrate_manifest_envelope(
    manifest: &Path,
    recorded_digest: Option<&str>,
    recomputed_digest: Option<&str>,
    invariant: Option<&'static str>,
    exit: Exit,
) -> Exit {
    // ADR 0037 §5: a successful digest match means the manifest body
    // matches the canonical BLAKE3 recorded inside it — `proof_state`
    // promotes to `full_chain_verified` only on the success path; any
    // failure (digest mismatch, missing digest, unreadable) leaves it
    // `unknown` so a consumer cannot mistake a refused verification
    // for an authoritative result.
    let proof_state = if exit == Exit::Ok && invariant.is_none() {
        ClaimProofState::FullChainVerified
    } else {
        ClaimProofState::Unknown
    };
    let truth_ceiling = restore_truth_ceiling_object(proof_state, AuthorityClass::Observed);
    let report = json!({
        "manifest": manifest.display().to_string(),
        "manifest_blake3_recorded": recorded_digest,
        "manifest_blake3_recomputed": recomputed_digest,
        "invariant": invariant,
        "mutated_store": false,
        "truth_ceiling": truth_ceiling,
    });
    let envelope = crate::output::Envelope::new(VERIFY_POST_MIGRATE_MANIFEST_COMMAND, exit, report);
    crate::output::emit(&envelope, exit)
}

fn run_verify_backup(args: VerifyBackupArgs) -> Exit {
    let verified = match verify_pre_v2_backup(&args.manifest) {
        Ok(verified) => verified,
        Err(exit) => return exit,
    };
    // ADR 0037 §5: `verify-backup` structurally verifies the bundle's
    // SQLite + JSONL artifacts against the manifest hashes — that's a
    // `full_chain_verified` proof state for the bundle contents, but
    // not an authority class promotion (the bundle is local evidence).
    let truth_ceiling =
        restore_truth_ceiling_object(ClaimProofState::FullChainVerified, AuthorityClass::Observed);
    let report = json!({
        "command": "restore.verify_backup",
        "manifest": args.manifest,
        "kind": "cortex_pre_v2_backup",
        "schema_version": verified.schema_version,
        "artifacts": [
            {
                "field": verified.sqlite_store.manifest_field,
                "path": verified.sqlite_store.path,
                "size_bytes": verified.sqlite_store.size_bytes,
                "blake3": verified.sqlite_store.blake3,
            },
            {
                "field": verified.jsonl_mirror.manifest_field,
                "path": verified.jsonl_mirror.path,
                "size_bytes": verified.jsonl_mirror.size_bytes,
                "blake3": verified.jsonl_mirror.blake3,
            }
        ],
        "restore_performed": false,
        "cutover_performed": false,
        "destructive_restore_supported": false,
        "mutated_store": false,
        "truth_ceiling": truth_ceiling,
    });
    match serde_json::to_string_pretty(&report) {
        Ok(output) => {
            println!("{output}");
            eprintln!(
                "cortex restore verify-backup: backup structure verified; destructive restore/cutover is not implemented. no state was changed."
            );
            Exit::Ok
        }
        Err(err) => {
            eprintln!("cortex restore verify-backup: failed to serialize report: {err}");
            Exit::Internal
        }
    }
}

fn run_preflight(args: PreflightArgs) -> Exit {
    let verified = match verify_pre_v2_backup(&args.manifest) {
        Ok(verified) => verified,
        Err(exit) => return exit,
    };
    let structural = verified_backup_report(&verified);

    let (semantic_diff, exit) = match args.candidate_store.as_deref() {
        None => (
            json!({
                "required": true,
                "executed": false,
                "status": "required_not_executed",
                "reason": "pass --candidate-store with an expanded candidate store to run read-only semantic diff",
            }),
            Exit::PreconditionUnmet,
        ),
        Some(candidate_store) => match semantic_preflight_report(
            args.current_store.as_deref(),
            candidate_store,
            args.acknowledge_recovery_risk,
        ) {
            Ok(result) => result,
            Err(exit) => return exit,
        },
    };

    let production_active_store_plan = if args.production_active_store_plan {
        Some(production_active_store_plan_report(
            exit,
            args.current_store.as_deref(),
            args.active_store_lock_marker.as_deref(),
        ))
    } else {
        None
    };
    let final_exit = if args.production_active_store_plan && exit == Exit::Ok {
        Exit::PreconditionUnmet
    } else {
        exit
    };

    // ADR 0026 #24: compose the preflight policy decision. The
    // `production_active_store_plan` contributor remains `Reject` until the
    // production gates land.
    let preflight_semantic_decision =
        semantic_decision_for_preflight_composition(&semantic_diff, exit);
    let preflight_decision = policy::compose_preflight_decision(
        preflight_semantic_decision.as_ref(),
        args.production_active_store_plan,
    );

    // ADR 0037 §5: preflight runs structural verification (full chain
    // verified on success) but is itself a read-only diagnostic that
    // does not promote claims. `proof_state` reflects the structural
    // pass when the semantic candidate executed.
    let preflight_proof_state = if exit == Exit::Ok {
        ClaimProofState::FullChainVerified
    } else {
        ClaimProofState::Unknown
    };
    let truth_ceiling =
        restore_truth_ceiling_object(preflight_proof_state, AuthorityClass::Observed);
    let report = json!({
        "command": "restore.preflight",
        "manifest": args.manifest,
        "structural_verification": structural,
        "semantic_diff": semantic_diff,
        "production_active_store_plan": production_active_store_plan.unwrap_or_else(|| json!({
            "requested": false,
        })),
        "policy_decision": policy::policy_decision_report(&preflight_decision),
        "restore_performed": false,
        "cutover_performed": false,
        "destructive_restore_supported": false,
        "mutated_store": false,
        "truth_ceiling": truth_ceiling,
    });
    match serde_json::to_string_pretty(&report) {
        Ok(output) => {
            println!("{output}");
            if args.production_active_store_plan {
                eprintln!(
                    "cortex restore preflight: production active-store restore plan is blocked by unsatisfied production gates. no state was changed."
                );
            } else {
                eprintln!(
                    "cortex restore preflight: structural verification completed; semantic diff status is reported above. no state was changed."
                );
            }
            final_exit
        }
        Err(err) => {
            eprintln!("cortex restore preflight: failed to serialize report: {err}");
            Exit::Internal
        }
    }
}

fn run_stage(args: StageArgs) -> Exit {
    if !args.acknowledge_destructive_restore {
        eprintln!(
            "cortex restore stage: --acknowledge-destructive-restore is required; no state was changed."
        );
        return Exit::PreconditionUnmet;
    }
    if args.stage_dir.exists() {
        eprintln!(
            "cortex restore stage: stage directory `{}` already exists; no state was changed.",
            args.stage_dir.display()
        );
        return Exit::PreconditionUnmet;
    }

    let verified = match verify_pre_v2_backup(&args.manifest) {
        Ok(verified) => verified,
        Err(exit) => return exit,
    };
    let tmp_stage_dir = temporary_stage_dir(&args.stage_dir);
    if tmp_stage_dir.exists() {
        eprintln!(
            "cortex restore stage: temporary stage directory `{}` already exists; no state was changed.",
            tmp_stage_dir.display()
        );
        return Exit::PreconditionUnmet;
    }
    if let Some(parent) = tmp_stage_dir.parent() {
        if !parent.exists() {
            eprintln!(
                "cortex restore stage: parent directory `{}` does not exist; no state was changed.",
                parent.display()
            );
            return Exit::PreconditionUnmet;
        }
    }
    if let Err(err) = fs::create_dir(&tmp_stage_dir) {
        eprintln!(
            "cortex restore stage: failed to create temporary stage directory `{}`: {err}. no state was changed.",
            tmp_stage_dir.display()
        );
        return Exit::PreconditionUnmet;
    }

    let staged_sqlite = tmp_stage_dir.join("cortex.db");
    let staged_jsonl = tmp_stage_dir.join("events.jsonl");
    if let Err(exit) = copy_verified_artifact(&verified.sqlite_store.path, &staged_sqlite) {
        cleanup_temporary_stage(&tmp_stage_dir);
        return exit;
    }
    if let Err(exit) = copy_verified_artifact(&verified.jsonl_mirror.path, &staged_jsonl) {
        cleanup_temporary_stage(&tmp_stage_dir);
        return exit;
    }

    let audit = match audit_verify_staged_jsonl(&staged_jsonl) {
        Ok(report) => report,
        Err(exit) => {
            cleanup_temporary_stage(&tmp_stage_dir);
            return exit;
        }
    };
    let (semantic_diff, semantic_exit) = match semantic_preflight_report(
        args.current_store.as_deref(),
        &staged_sqlite,
        args.acknowledge_recovery_risk,
    ) {
        Ok(result) => result,
        Err(exit) => {
            cleanup_temporary_stage(&tmp_stage_dir);
            return exit;
        }
    };
    if semantic_exit != Exit::Ok {
        cleanup_temporary_stage(&tmp_stage_dir);
        return semantic_exit;
    }

    if let Err(err) = fs::rename(&tmp_stage_dir, &args.stage_dir) {
        cleanup_temporary_stage(&tmp_stage_dir);
        eprintln!(
            "cortex restore stage: failed to finalize stage directory `{}`: {err}. active store was not changed.",
            args.stage_dir.display()
        );
        return Exit::Internal;
    }

    // ADR 0026 #25: compose the stage decision. Boolean ack is the
    // `restore.stage.destructive_intent` contributor; the operator's
    // `--acknowledge-recovery-risk` is the scoped BreakGlassAuthorization
    // with `reason_code=RestoreRecovery`.
    let stage_semantic_decision =
        semantic_decision_for_preflight_composition(&semantic_diff, semantic_exit);
    let stage_decision = policy::compose_stage_decision(
        args.acknowledge_destructive_restore,
        stage_semantic_decision.as_ref(),
        args.acknowledge_recovery_risk,
        &format!("stage_dir:{}", args.stage_dir.display()),
    );
    // ADR 0037 §5: stage runs the same structural + audit + semantic
    // chain as preflight on the staged candidate. The operator's
    // `--acknowledge-recovery-risk` lifts the authority class to
    // `verified` (scoped BreakGlass), but the runtime mode stays
    // `local_unsigned` because the candidate is local evidence.
    let stage_authority = if args.acknowledge_recovery_risk {
        AuthorityClass::Verified
    } else {
        AuthorityClass::Observed
    };
    let truth_ceiling =
        restore_truth_ceiling_object(ClaimProofState::FullChainVerified, stage_authority);
    let report = json!({
        "command": "restore.stage",
        "manifest": args.manifest,
        "stage_dir": args.stage_dir,
        "structural_verification": verified_backup_report(&verified),
        "audit_verification": audit_report(&audit),
        "semantic_diff": semantic_diff,
        "policy_decision": policy::policy_decision_report(&stage_decision),
        "restore_performed": false,
        "cutover_performed": false,
        "destructive_restore_supported": false,
        "destructive_restore_staged": true,
        "mutated_store": false,
        "truth_ceiling": truth_ceiling,
    });
    match serde_json::to_string_pretty(&report) {
        Ok(output) => {
            println!("{output}");
            eprintln!(
                "cortex restore stage: restore candidate staged after structural, audit, and semantic guards. active store was not changed."
            );
            Exit::Ok
        }
        Err(err) => {
            eprintln!("cortex restore stage: failed to serialize report: {err}");
            Exit::Internal
        }
    }
}

fn run_apply_stage(args: ApplyStageArgs) -> Exit {
    if !args.acknowledge_active_store_replacement || !args.acknowledge_temp_test_data_dir {
        eprintln!(
            "cortex restore apply-stage: --acknowledge-active-store-replacement and --acknowledge-temp-test-data-dir are required; active store was not changed."
        );
        return Exit::PreconditionUnmet;
    }
    if !args.stage_dir.is_dir() {
        eprintln!(
            "cortex restore apply-stage: stage directory `{}` does not exist; active store was not changed.",
            args.stage_dir.display()
        );
        return Exit::PreconditionUnmet;
    }

    let layout = match DataLayout::resolve(None, None) {
        Ok(layout) => layout,
        Err(exit) => return exit,
    };
    if !is_temp_test_data_dir(&layout.data_dir) {
        eprintln!(
            "cortex restore apply-stage: active data directory `{}` is not under the system temp directory; active store was not changed.",
            layout.data_dir.display()
        );
        return Exit::PreconditionUnmet;
    }

    let verified = match verify_pre_v2_backup(&args.manifest) {
        Ok(verified) => verified,
        Err(exit) => return exit,
    };
    let staged_sqlite = args.stage_dir.join("cortex.db");
    let staged_jsonl = args.stage_dir.join("events.jsonl");
    if let Err(exit) = verify_staged_artifact(&staged_sqlite, &verified.sqlite_store) {
        return exit;
    }
    if let Err(exit) = verify_staged_artifact(&staged_jsonl, &verified.jsonl_mirror) {
        return exit;
    }
    let audit = match audit_verify_staged_jsonl(&staged_jsonl) {
        Ok(report) => report,
        Err(exit) => return exit,
    };
    let (semantic_diff, semantic_exit) = match semantic_preflight_report(
        Some(&layout.db_path),
        &staged_sqlite,
        args.acknowledge_recovery_risk,
    ) {
        Ok(result) => result,
        Err(exit) => return exit,
    };
    if semantic_exit != Exit::Ok {
        eprintln!(
            "cortex restore apply-stage: semantic restore gate rejected the candidate; active store was not changed."
        );
        return semantic_exit;
    }

    let active_db_before_hash = match blake3_file(&layout.db_path, "active_db_before_restore") {
        Ok(hash) => Some(hash),
        Err(exit) => return exit,
    };
    let audit_entry =
        match restore_apply_stage_audit_entry(&args, &layout, &verified, active_db_before_hash) {
            Ok(entry) => entry,
            Err(exit) => return exit,
        };
    let recovery_evidence =
        match apply_staged_active_store(&layout, &staged_sqlite, &staged_jsonl, &audit_entry) {
            Ok(recovery_evidence) => recovery_evidence,
            Err(exit) => return exit,
        };
    let post_restore_verification = match post_restore_verification_report(
        &verified,
        &layout,
        &staged_sqlite,
        args.acknowledge_recovery_risk,
        args.post_restore_anchor.as_deref(),
        args.post_restore_anchor_history.as_deref(),
    ) {
        Ok(report) => report,
        Err(exit) => {
            return match restore_current_backups(&layout, &recovery_evidence) {
                Ok(()) => {
                    eprintln!(
                        "cortex restore apply-stage: post-restore verification failed after active replacement; active backups were restored from recovery evidence `{}`. active store was returned to its pre-apply state.",
                        recovery_evidence.manifest_path.display()
                    );
                    exit
                }
                Err(err) => {
                    eprintln!(
                        "cortex restore apply-stage: post-restore verification failed after active replacement and rollback from recovery evidence `{}` failed: {err}. active store may require manual recovery before continuing writes.",
                        recovery_evidence.manifest_path.display()
                    );
                    err.to_exit()
                }
            };
        }
    };

    // ADR 0026 #26: compose the apply-stage policy decision.
    // `post_restore_anchor` outcome maps from the post-restore verification
    // status; `operator_temporal_authority` is `Allow` for the temp-test
    // path (the operator has implicit local authority on the temp data dir).
    let apply_decision = policy::compose_apply_decision(
        post_restore_anchor_outcome_from_report(&post_restore_verification),
        "post-restore anchor verified against active JSONL (temp-test scope)",
        cortex_core::PolicyOutcome::Allow,
        "operator temporal authority bound by temp-test data dir scope",
        args.acknowledge_recovery_risk,
        "restore.apply_stage",
        &format!("active_db:{}", layout.db_path.display()),
    );
    // ADR 0037 §5: apply-stage is the destructive temp-test cutover.
    // The structural + audit + semantic + post-restore-verification
    // chain on the success path gives `full_chain_verified` proof
    // state; the operator's destructive acknowledgments lift the
    // authority class to `verified` (BreakGlass scope).
    let truth_ceiling =
        restore_truth_ceiling_object(ClaimProofState::FullChainVerified, AuthorityClass::Verified);
    let report = json!({
        "command": "restore.apply_stage",
        "manifest": args.manifest,
        "stage_dir": args.stage_dir,
        "active_db": layout.db_path,
        "active_event_log": layout.event_log_path,
        "structural_verification": verified_backup_report(&verified),
        "staged_artifacts": "verified",
        "audit_verification": audit_report(&audit),
        "semantic_diff": semantic_diff,
        "post_restore_verification": post_restore_verification,
        "policy_decision": policy::policy_decision_report(&apply_decision),
        "recovery_evidence": {
            "status": "prepared_before_active_replacement",
            "manifest": recovery_evidence.manifest_path,
            "active_db_backup": recovery_evidence.active_db_backup,
            "active_event_log_backup": recovery_evidence.active_event_log_backup,
        },
        "audit_record_id": audit_entry.id,
        "audit_operation": audit_entry.operation,
        "restore_performed": true,
        "cutover_performed": true,
        "destructive_restore_supported": true,
        "mutated_store": true,
        "truth_ceiling": truth_ceiling,
    });
    match serde_json::to_string_pretty(&report) {
        Ok(output) => {
            println!("{output}");
            eprintln!(
                "cortex restore apply-stage: staged candidate applied to temp-test active store after manifest, audit, and semantic guards. active store was mutated."
            );
            Exit::Ok
        }
        Err(err) => {
            eprintln!("cortex restore apply-stage: failed to serialize report: {err}");
            Exit::Internal
        }
    }
}

fn run_recover_apply(args: RecoverApplyArgs) -> Exit {
    if !args.acknowledge_current_backup_restore || !args.acknowledge_temp_test_data_dir {
        eprintln!(
            "cortex restore recover-apply: --acknowledge-current-backup-restore and --acknowledge-temp-test-data-dir are required; active store was not changed."
        );
        return Exit::PreconditionUnmet;
    }

    let manifest = match read_apply_recovery_manifest(&args.manifest) {
        Ok(manifest) => manifest,
        Err(exit) => return exit,
    };
    if let Err(exit) = verify_apply_recovery_scope(&manifest) {
        return exit;
    }
    if let Err(exit) = verify_apply_recovery_backup(
        &args.manifest,
        "active_db_backup",
        &manifest.active_backups.db,
    ) {
        return exit;
    }
    if let Err(exit) = verify_apply_recovery_backup(
        &args.manifest,
        "active_event_log_backup",
        &manifest.active_backups.event_log,
    ) {
        return exit;
    }
    if let Err(exit) = verify_apply_recovery_targets(&manifest) {
        return exit;
    }

    // Phase 2.6 closure: revalidate operator temporal authority for the
    // bound `--attestation` key against the durable `authority_key_timeline`
    // before any mutation. `minimum_trust_tier = Operator` per audit §6.2 —
    // recover-apply is the destructive doctrine root that restores
    // current backups from a previous apply-stage. Absent attestation
    // refuses with the stable invariant. Test fixtures must seed the
    // operator-key timeline before running this command (mirror the
    // `cli_phase2::seed_operator_authority` shape).
    let operator_temporal_ok =
        match revalidate_recover_apply_operator_temporal_authority(args.attestation.as_deref()) {
            Ok(ok) => ok,
            Err(exit) => return exit,
        };

    let active_db_before_hash = match blake3_file(&manifest.active.db, "active_db_before_recovery")
    {
        Ok(hash) => Some(hash),
        Err(exit) => return exit,
    };
    let audit_entry =
        match restore_recover_apply_audit_entry(&args, &manifest, active_db_before_hash) {
            Ok(entry) => entry,
            Err(exit) => return exit,
        };
    if let Err(exit) = restore_apply_recovery_backups(&manifest, &audit_entry) {
        return exit;
    }

    // ADR 0026 #27: compose the recover-apply policy decision. Manifest
    // digest and backup digest were verified above; operator temporal
    // authority is now derived from `AuthorityRepo::revalidate` against
    // the durable key/principal timeline (Phase 2.6 closure).
    let recover_decision = policy::compose_recover_apply_decision(
        true,
        true,
        operator_temporal_ok,
        false,
        &format!("recovery_manifest:{}", args.manifest.display()),
    );
    // ADR 0037 §5: recover-apply is the destructive rollback that
    // restores the pre-apply-stage backups. All digests verified above
    // give `full_chain_verified` proof state; the operator-signed
    // recovery manifest lifts the authority class to `verified`.
    let truth_ceiling =
        restore_truth_ceiling_object(ClaimProofState::FullChainVerified, AuthorityClass::Verified);
    let report = json!({
        "command": "restore.recover_apply",
        "manifest": args.manifest,
        "scope": manifest.scope,
        "active_db": manifest.active.db,
        "active_event_log": manifest.active.event_log,
        "active_db_backup": manifest.active_backups.db.path,
        "active_event_log_backup": manifest.active_backups.event_log.path,
        "recovery_status": "current_backups_restored_with_command_audit_row",
        "policy_decision": policy::policy_decision_report(&recover_decision),
        "audit_record_id": audit_entry.id,
        "audit_operation": audit_entry.operation,
        "restore_performed": true,
        "cutover_performed": true,
        "destructive_restore_supported": true,
        "mutated_store": true,
        "truth_ceiling": truth_ceiling,
    });
    match serde_json::to_string_pretty(&report) {
        Ok(output) => {
            println!("{output}");
            eprintln!(
                "cortex restore recover-apply: current backups restored to temp-test active store from apply-stage recovery manifest, then a command audit row was appended. active store was mutated."
            );
            Exit::Ok
        }
        Err(err) => {
            eprintln!("cortex restore recover-apply: failed to serialize report: {err}");
            Exit::Internal
        }
    }
}

/// Phase 2.6 closure: load operator attestation key from the supplied
/// `--attestation <PATH>` and revalidate operator temporal authority
/// against the durable `authority_key_timeline` /
/// `authority_principal_timeline`. Returns `Ok(true)` only when the
/// revalidation reports `valid_now`; otherwise emits the stable
/// invariant and returns the corresponding [`Exit`].
fn revalidate_recover_apply_operator_temporal_authority(
    attestation_path: Option<&Path>,
) -> Result<bool, Exit> {
    let invariant = revalidation_failed_invariant("restore.recover_apply");
    let Some(path) = attestation_path else {
        eprintln!(
            "cortex restore recover-apply: {invariant}: --attestation <PATH> is required; recover-apply is a destructive doctrine root and requires durable operator-key timeline revalidation (ADR 0023 / ADR 0026 §4 hard wall). active store was not changed."
        );
        return Err(Exit::PreconditionUnmet);
    };
    let bytes = fs::read(path).map_err(|err| {
        eprintln!(
            "cortex restore recover-apply: {invariant}: cannot read --attestation key file `{}`: {err}. active store was not changed.",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    if bytes.len() != 32 {
        eprintln!(
            "cortex restore recover-apply: {invariant}: --attestation key file `{}` must be exactly 32 raw bytes (Ed25519 seed); got {} bytes. active store was not changed.",
            path.display(),
            bytes.len()
        );
        return Err(Exit::PreconditionUnmet);
    }
    let mut seed = [0u8; 32];
    seed.copy_from_slice(&bytes);
    let attestor = InMemoryAttestor::from_seed(&seed);
    let pool = open_default_store("restore recover-apply")?;
    let now = chrono::Utc::now();
    let contribution = revalidate_operator_temporal_authority(
        &pool,
        policy::RECOVER_APPLY_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID,
        attestor.key_id(),
        now,
        TrustTier::Operator,
    )
    .map_err(|err| {
        eprintln!(
            "cortex restore recover-apply: {invariant}: failed to read authority timeline for key {}: {err}. active store was not changed.",
            attestor.key_id(),
        );
        Exit::PreconditionUnmet
    })?;
    if !contribution.report.valid_now {
        let reasons = contribution
            .report
            .reasons
            .iter()
            .map(|reason| reason.wire_str())
            .collect::<Vec<_>>()
            .join(",");
        eprintln!(
            "cortex restore recover-apply: {invariant}: operator temporal authority current use blocked for key {} (reasons: {reasons}). active store was not changed.",
            contribution.report.key_id,
        );
        return Err(Exit::PreconditionUnmet);
    }
    Ok(true)
}

fn verified_backup_report(verified: &VerifiedBackup) -> serde_json::Value {
    json!({
        "status": "verified",
        "kind": "cortex_pre_v2_backup",
        "schema_version": verified.schema_version,
        "artifacts": [
            {
                "field": verified.sqlite_store.manifest_field,
                "path": verified.sqlite_store.path,
                "size_bytes": verified.sqlite_store.size_bytes,
                "blake3": verified.sqlite_store.blake3,
            },
            {
                "field": verified.jsonl_mirror.manifest_field,
                "path": verified.jsonl_mirror.path,
                "size_bytes": verified.jsonl_mirror.size_bytes,
                "blake3": verified.jsonl_mirror.blake3,
            }
        ],
    })
}

fn production_active_store_plan_report(
    preflight_exit: Exit,
    current_store: Option<&Path>,
    lock_marker: Option<&Path>,
) -> serde_json::Value {
    let semantic_diff_gate = if preflight_exit == Exit::Ok {
        "satisfied"
    } else {
        "blocked"
    };
    let active_store_lock = active_store_lock_preflight_report(current_store, lock_marker);
    let active_store_lock_gate = if active_store_lock["exclusive_lock_acquire_release_verified"]
        .as_bool()
        .unwrap_or(false)
    {
        json!({
            "gate": "active_store_lock",
            "status": "preflight_only",
            "reason": "exclusive temp marker acquire/release preflight succeeded, but production restore still lacks a held lock and writer-freeze protocol for the mutation window",
        })
    } else {
        json!({
            "gate": "active_store_lock",
            "status": "missing",
            "reason": "production restore must exclude concurrent Cortex writers before active path replacement",
        })
    };
    json!({
        "requested": true,
        "status": "blocked",
        "decision": "precondition_unmet",
        "restore_mode": "production_active_store",
        "mutation_supported": false,
        "mutation_command_available": false,
        "preflight_gates": {
            "manifest_and_artifact_verification": "satisfied",
            "semantic_diff": semantic_diff_gate,
            "active_store_lock": active_store_lock["status"],
            "schema_v2_cutover": "blocked",
            "post_restore_verification": "blocked",
        },
        "active_store_lock": active_store_lock,
        "post_restore_verification_gates": production_post_restore_verification_gates(),
        "required_gates": [
            {
                "gate": "schema_v2_cutover",
                "status": "missing",
                "reason": format!("production active-store restore remains blocked while cortex_core::SCHEMA_VERSION is {} and the schema v2 atomic cutover is incomplete", cortex_core::SCHEMA_VERSION),
            },
            {
                "gate": "production_identity_attestation",
                "status": "missing",
                "reason": "production active-store restore must bind the operator and recovery authority before mutation",
            },
            active_store_lock_gate,
            {
                "gate": "atomic_cutover_protocol",
                "status": "missing",
                "reason": "production restore must define crash-safe SQLite and JSONL replacement with rollback evidence",
            },
            {
                "gate": "external_anchor_revalidation",
                "status": "missing",
                "reason": "production restore must revalidate audit chain authority against the selected anchor strategy",
            },
            {
                "gate": "post_restore_audit_and_semantic_recheck",
                "status": "missing",
                "reason": "production restore must verify chain, schema, and semantic snapshot after cutover before reopening writes",
            },
            {
                "gate": "post_restore_anchor_revalidation",
                "status": "missing",
                "reason": "production restore must revalidate the restored JSONL against the configured external anchor surface after cutover",
            }
        ],
        "safe_next_step": "stage and apply the candidate only in a temp-test data directory; production active-store mutation remains unavailable",
    })
}

fn production_post_restore_verification_gates() -> serde_json::Value {
    json!({
        "status": "blocked",
        "executed": false,
        "reason": "post-restore gates require a completed production cutover protocol and configured external anchor authority",
        "manifest_artifacts": {
            "required": true,
            "status": "blocked_until_cutover",
        },
        "jsonl_audit": {
            "required": true,
            "status": "blocked_until_cutover",
        },
        "semantic_diff": {
            "required": true,
            "status": "blocked_until_cutover",
        },
        "anchors": {
            "required": true,
            "status": "missing_external_anchor_authority",
        },
    })
}

fn active_store_lock_preflight_report(
    current_store: Option<&Path>,
    lock_marker: Option<&Path>,
) -> serde_json::Value {
    let marker_path = lock_marker
        .map(Path::to_path_buf)
        .unwrap_or_else(|| default_active_store_lock_marker(current_store));
    let marker_exists = marker_path.exists();
    if marker_exists {
        return json!({
            "status": "blocked_existing_lock_marker",
            "lock_marker": marker_path,
            "marker_exists": true,
            "absence_required": true,
            "absence_satisfied": false,
            "exclusive_lock_acquired": false,
            "exclusive_lock_acquire_attempted": false,
            "exclusive_lock_acquired_during_probe": false,
            "exclusive_lock_released": false,
            "exclusive_lock_acquire_release_verified": false,
            "probe_scope": "not_attempted_existing_marker",
            "reason": "an active-store lock marker already exists; production restore must not proceed while another writer or restore may hold the active store",
        });
    }

    let marker_parent = marker_path.parent().unwrap_or_else(|| Path::new("."));
    if !marker_parent.exists() {
        return json!({
            "status": "lock_marker_parent_missing",
            "lock_marker": marker_path,
            "marker_exists": false,
            "absence_required": true,
            "absence_satisfied": true,
            "exclusive_lock_acquired": false,
            "exclusive_lock_acquire_attempted": false,
            "exclusive_lock_acquired_during_probe": false,
            "exclusive_lock_released": false,
            "exclusive_lock_acquire_release_verified": false,
            "probe_scope": "not_attempted_missing_parent",
            "reason": "active-store lock marker parent does not exist; production restore still lacks a usable lock path",
        });
    }
    if !is_temp_test_data_dir(marker_parent) {
        return json!({
            "status": "temp_lock_probe_not_executed",
            "lock_marker": marker_path,
            "marker_exists": false,
            "absence_required": true,
            "absence_satisfied": true,
            "exclusive_lock_acquired": false,
            "exclusive_lock_acquire_attempted": false,
            "exclusive_lock_acquired_during_probe": false,
            "exclusive_lock_released": false,
            "exclusive_lock_acquire_release_verified": false,
            "probe_scope": "not_attempted_non_temp_marker",
            "reason": "exclusive lock acquisition is implemented only as a temp-test/report preflight probe; production restore still lacks a held lock protocol",
        });
    }

    match acquire_release_active_store_lock_probe(&marker_path) {
        Ok(()) => json!({
            "status": "temp_lock_acquire_release_verified",
            "lock_marker": marker_path,
            "marker_exists": false,
            "absence_required": true,
            "absence_satisfied": true,
            "exclusive_lock_acquired": false,
            "exclusive_lock_acquire_attempted": true,
            "exclusive_lock_acquired_during_probe": true,
            "exclusive_lock_released": true,
            "exclusive_lock_acquire_release_verified": true,
            "probe_scope": "temp_test_report_only",
            "reason": "exclusive temp marker create_new acquisition and release succeeded; production restore remains blocked because no lock is held across mutation",
        }),
        Err(ActiveStoreLockProbeError::AlreadyExists) => json!({
            "status": "blocked_existing_lock_marker",
            "lock_marker": marker_path,
            "marker_exists": true,
            "absence_required": true,
            "absence_satisfied": false,
            "exclusive_lock_acquired": false,
            "exclusive_lock_acquire_attempted": true,
            "exclusive_lock_acquired_during_probe": false,
            "exclusive_lock_released": false,
            "exclusive_lock_acquire_release_verified": false,
            "probe_scope": "temp_test_report_only",
            "reason": "exclusive lock probe observed an existing active-store marker; production restore must not proceed while another writer or restore may hold the active store",
        }),
        Err(ActiveStoreLockProbeError::Io(message)) => json!({
            "status": "lock_probe_failed",
            "lock_marker": marker_path,
            "marker_exists": marker_path.exists(),
            "absence_required": true,
            "absence_satisfied": !marker_path.exists(),
            "exclusive_lock_acquired": false,
            "exclusive_lock_acquire_attempted": true,
            "exclusive_lock_acquired_during_probe": false,
            "exclusive_lock_released": false,
            "exclusive_lock_acquire_release_verified": false,
            "probe_scope": "temp_test_report_only",
            "reason": message,
        }),
    }
}

fn default_active_store_lock_marker(current_store: Option<&Path>) -> PathBuf {
    if let Some(parent) = current_store.and_then(Path::parent) {
        return parent.join(".cortex-restore-active-store.lock");
    }
    DataLayout::resolve(None, None)
        .map(|layout| layout.data_dir.join(".cortex-restore-active-store.lock"))
        .unwrap_or_else(|_| PathBuf::from(".cortex-restore-active-store.lock"))
}

#[derive(Debug)]
enum ActiveStoreLockProbeError {
    AlreadyExists,
    Io(String),
}

fn acquire_release_active_store_lock_probe(
    marker_path: &Path,
) -> Result<(), ActiveStoreLockProbeError> {
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(marker_path)
        .map_err(|err| {
            if err.kind() == ErrorKind::AlreadyExists {
                ActiveStoreLockProbeError::AlreadyExists
            } else {
                ActiveStoreLockProbeError::Io(format!(
                    "failed to acquire exclusive active-store lock probe `{}`: {err}",
                    marker_path.display()
                ))
            }
        })?;
    let payload = format!(
        "cortex restore active-store lock preflight\npid={}\nscope=temp-test-report-only\n",
        std::process::id()
    );
    if let Err(err) = file
        .write_all(payload.as_bytes())
        .and_then(|()| file.sync_all())
    {
        let _ = fs::remove_file(marker_path);
        return Err(ActiveStoreLockProbeError::Io(format!(
            "failed to write exclusive active-store lock probe `{}`: {err}",
            marker_path.display()
        )));
    }
    drop(file);
    fs::remove_file(marker_path).map_err(|err| {
        ActiveStoreLockProbeError::Io(format!(
            "failed to release exclusive active-store lock probe `{}`: {err}",
            marker_path.display()
        ))
    })
}

fn post_restore_anchor_outcome_from_report(
    post_restore: &serde_json::Value,
) -> cortex_core::PolicyOutcome {
    let executed = post_restore
        .get("anchors")
        .and_then(|a| a.get("executed"))
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    if executed {
        cortex_core::PolicyOutcome::Allow
    } else {
        // Local-only / not-configured: warning rather than reject; the
        // operator can elevate via BreakGlass if they accept the risk.
        cortex_core::PolicyOutcome::Warn
    }
}

fn semantic_decision_for_preflight_composition(
    semantic_diff: &serde_json::Value,
    exit: Exit,
) -> Option<cortex_core::PolicyDecision> {
    // Synthesize a stand-in `PolicyDecision` so the preflight composer can
    // see the semantic-diff outcome. We do not have direct access to the
    // composed decision after `semantic_preflight_report` returned, so we
    // mint a one-contributor synthesis using the recorded exit code; the
    // full per-rule decomposition was already emitted inside `semantic_diff`.
    use cortex_core::{compose_policy_outcomes, PolicyContribution, PolicyOutcome};
    if semantic_diff
        .get("executed")
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
    {
        let outcome = match exit {
            Exit::Ok => PolicyOutcome::Allow,
            _ => PolicyOutcome::Reject,
        };
        let contribution = PolicyContribution::new(
            policy::PREFLIGHT_SEMANTIC_DIFF_RULE_ID,
            outcome,
            "synthesized from semantic_preflight_report exit code",
        )
        .expect("static rule id is non-empty");
        Some(compose_policy_outcomes(vec![contribution], None))
    } else {
        None
    }
}

fn semantic_preflight_report(
    current_store: Option<&Path>,
    candidate_store: &Path,
    acknowledge_recovery_risk: bool,
) -> Result<(serde_json::Value, Exit), Exit> {
    let current = match current_store {
        Some(current_store) => read_store_snapshot(current_store, "current")?,
        None => {
            let layout = DataLayout::resolve(None, None)?;
            read_store_snapshot(&layout.db_path, "current")?
        }
    };
    let candidate = read_store_snapshot(candidate_store, "candidate")?;
    let diff = current.diff_against_restore(&candidate);
    // ADR 0026 #23/#24/#25/#26: surface the composed policy decision on
    // every diff lens. The legacy `RestoreDecision` shape is preserved for
    // backwards-compatible JSON consumers.
    let composed = policy::compose_semantic_diff_decision(
        &diff,
        acknowledge_recovery_risk,
        "restore.semantic_diff",
        &format!("candidate_store:{}", candidate_store.display()),
    );
    let decision = composed.legacy;
    let exit = match decision {
        RestoreDecision::Clean | RestoreDecision::Warning { .. } => Exit::Ok,
        RestoreDecision::PreconditionUnmet { .. } => Exit::PreconditionUnmet,
    };
    Ok((
        json!({
            "required": true,
            "executed": true,
            "status": diff.severity(),
            "current_snapshot_id": diff.current_snapshot_id,
            "candidate_snapshot_id": diff.restored_snapshot_id,
            "decision": decision,
            "policy_decision": policy::policy_decision_report(&composed.decision),
            "change_count": diff.changes.len(),
            "changes": diff.changes,
        }),
        exit,
    ))
}

fn temporary_stage_dir(stage_dir: &Path) -> PathBuf {
    let file_name = stage_dir
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("restore-stage");
    stage_dir.with_file_name(format!(".{file_name}.tmp-{}", std::process::id()))
}

fn copy_verified_artifact(source: &Path, destination: &Path) -> Result<(), Exit> {
    fs::copy(source, destination).map(|_| ()).map_err(|err| {
        eprintln!(
            "cortex restore stage: failed to copy verified artifact `{}` to `{}`: {err}. active store was not changed.",
            source.display(),
            destination.display()
        );
        Exit::Internal
    })
}

fn verify_staged_artifact(path: &Path, expected: &VerifiedArtifact) -> Result<(), Exit> {
    let metadata = fs::metadata(path).map_err(|_| {
        eprintln!(
            "cortex restore apply-stage: staged `{}` artifact `{}` is missing. active store was not changed.",
            expected.manifest_field,
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    if !metadata.is_file() {
        eprintln!(
            "cortex restore apply-stage: staged `{}` artifact `{}` is not a file. active store was not changed.",
            expected.manifest_field,
            path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    if metadata.len() != expected.size_bytes {
        eprintln!(
            "cortex restore apply-stage: staged `{}` artifact `{}` size mismatch: manifest={}, actual={}. active store was not changed.",
            expected.manifest_field,
            path.display(),
            expected.size_bytes,
            metadata.len()
        );
        return Err(Exit::QuarantinedInput);
    }
    let actual_blake3 = blake3_file(path, expected.manifest_field)?;
    if actual_blake3 != expected.blake3 {
        eprintln!(
            "cortex restore apply-stage: staged `{}` artifact `{}` digest mismatch: manifest={}, actual={}. active store was not changed.",
            expected.manifest_field,
            path.display(),
            expected.blake3,
            actual_blake3
        );
        return Err(Exit::QuarantinedInput);
    }
    Ok(())
}

fn verify_active_jsonl_artifact(path: &Path, expected: &VerifiedArtifact) -> Result<(), Exit> {
    let metadata = fs::metadata(path).map_err(|_| {
        eprintln!(
            "cortex restore apply-stage: post-restore active `{}` artifact `{}` is missing. recovery evidence may be required before continuing writes.",
            expected.manifest_field,
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    if !metadata.is_file() {
        eprintln!(
            "cortex restore apply-stage: post-restore active `{}` artifact `{}` is not a file. recovery evidence may be required before continuing writes.",
            expected.manifest_field,
            path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    if metadata.len() != expected.size_bytes {
        eprintln!(
            "cortex restore apply-stage: post-restore active `{}` artifact `{}` size mismatch: manifest={}, actual={}. recovery evidence may be required before continuing writes.",
            expected.manifest_field,
            path.display(),
            expected.size_bytes,
            metadata.len()
        );
        return Err(Exit::QuarantinedInput);
    }
    let actual_blake3 = blake3_file(path, expected.manifest_field)?;
    if actual_blake3 != expected.blake3 {
        eprintln!(
            "cortex restore apply-stage: post-restore active `{}` artifact `{}` digest mismatch: manifest={}, actual={}. recovery evidence may be required before continuing writes.",
            expected.manifest_field,
            path.display(),
            expected.blake3,
            actual_blake3
        );
        return Err(Exit::QuarantinedInput);
    }
    Ok(())
}

fn post_restore_verification_report(
    verified: &VerifiedBackup,
    layout: &DataLayout,
    staged_sqlite: &Path,
    acknowledge_recovery_risk: bool,
    anchor: Option<&Path>,
    anchor_history: Option<&Path>,
) -> Result<serde_json::Value, Exit> {
    verify_active_jsonl_artifact(&layout.event_log_path, &verified.jsonl_mirror)?;
    let audit = audit_verify_active_jsonl(&layout.event_log_path)?;
    let (mut semantic_diff, semantic_exit) = semantic_preflight_report(
        Some(staged_sqlite),
        &layout.db_path,
        acknowledge_recovery_risk,
    )?;
    if semantic_exit != Exit::Ok {
        eprintln!(
            "cortex restore apply-stage: post-restore semantic gate rejected the active store. recovery evidence may be required before continuing writes."
        );
        return Err(semantic_exit);
    }
    if let Some(object) = semantic_diff.as_object_mut() {
        object.insert(
            "comparison".to_string(),
            json!("staged_candidate_to_restored_active_store"),
        );
    }
    let anchors = post_restore_anchor_report(&layout.event_log_path, anchor, anchor_history)?;
    let production_anchor_authority = anchors["production_anchor_authority"]
        .as_bool()
        .unwrap_or(false);

    Ok(json!({
        "status": if production_anchor_authority {
            "verified"
        } else {
            "verified_for_temp_test_anchor_authority_unproven"
        },
        "manifest_artifacts": {
            "status": "source_verified_active_jsonl_verified_sqlite_payload_semantically_verified",
            "sqlite_store": {
                "status": "source_verified_before_cutover",
                "restored_payload_blake3": verified.sqlite_store.blake3,
                "active_exact_digest": "not_claimed_final_sqlite_contains_command_audit_row",
                "final_active_digest_claimed": false,
                "path": layout.db_path,
                "manifest_blake3": verified.sqlite_store.blake3,
            },
            "jsonl_mirror": {
                "status": "active_digest_verified",
                "path": layout.event_log_path,
                "manifest_blake3": verified.jsonl_mirror.blake3,
            },
        },
        "jsonl_audit": audit_report(&audit),
        "semantic_diff": semantic_diff,
        "anchors": anchors,
        "production_eligible": false,
        "production_blockers": [
            "schema_v2_cutover_incomplete",
            "production_lock_not_held_across_mutation",
            "external_anchor_authority_unproven",
            "production_identity_attestation_missing",
        ],
    }))
}

fn post_restore_anchor_report(
    event_log_path: &Path,
    anchor: Option<&Path>,
    anchor_history: Option<&Path>,
) -> Result<serde_json::Value, Exit> {
    if anchor.is_none() && anchor_history.is_none() {
        return Ok(json!({
            "required_for_production": true,
            "executed": false,
            "status": "not_configured",
            "single_anchor": null,
            "anchor_history": null,
            "production_anchor_authority": false,
            "reason": "no post-restore anchor or anchor history was provided; temp-test apply may continue, but production restore remains blocked",
        }));
    }

    let single_anchor = match anchor {
        Some(anchor_path) => verify_post_restore_anchor(event_log_path, anchor_path)?,
        None => json!({
            "requested": false,
        }),
    };
    let anchor_history = match anchor_history {
        Some(history_path) => verify_post_restore_anchor_history(event_log_path, history_path)?,
        None => json!({
            "requested": false,
        }),
    };

    Ok(json!({
        "required_for_production": true,
        "executed": true,
        "status": "verified_local_weak_anchor_evidence",
        "single_anchor": single_anchor,
        "anchor_history": anchor_history,
        "production_anchor_authority": false,
        "reason": "local anchor verification passed where provided, but local anchors do not prove disjoint external append-only authority for production restore",
    }))
}

fn verify_post_restore_anchor(
    event_log_path: &Path,
    anchor_path: &Path,
) -> Result<serde_json::Value, Exit> {
    let text = fs::read_to_string(anchor_path).map_err(|err| {
        eprintln!(
            "cortex restore apply-stage: cannot read post-restore anchor `{}`: {err}. recovery evidence may be required before continuing writes.",
            anchor_path.display()
        );
        Exit::PreconditionUnmet
    })?;
    let anchor = parse_anchor(&text).map_err(|err| {
        eprintln!(
            "cortex restore apply-stage: invalid post-restore anchor `{}`: {err}. recovery evidence may be required before continuing writes.",
            anchor_path.display()
        );
        Exit::PreconditionUnmet
    })?;
    match verify_anchor(event_log_path, &anchor) {
        Ok(verified) => Ok(json!({
            "requested": true,
            "status": "verified",
            "path": anchor_path,
            "event_count": verified.anchor.event_count,
            "rows_scanned": verified.db_count,
        })),
        Err(err) => {
            eprintln!(
                "cortex restore apply-stage: post-restore anchor verification failed for `{}` against `{}`: {err}. recovery evidence may be required before continuing writes.",
                anchor_path.display(),
                event_log_path.display()
            );
            Err(map_anchor_verify_err(&err))
        }
    }
}

fn verify_post_restore_anchor_history(
    event_log_path: &Path,
    history_path: &Path,
) -> Result<serde_json::Value, Exit> {
    match verify_anchor_history(event_log_path, history_path) {
        Ok(verified) => Ok(json!({
            "requested": true,
            "status": "verified",
            "path": history_path,
            "anchors_verified": verified.anchors_verified,
            "latest_event_count": verified.latest_anchor.event_count,
            "rows_scanned": verified.db_count,
        })),
        Err(err) => {
            eprintln!(
                "cortex restore apply-stage: post-restore anchor history verification failed for `{}` against `{}`: {err}. recovery evidence may be required before continuing writes.",
                history_path.display(),
                event_log_path.display()
            );
            Err(map_anchor_history_verify_err(&err))
        }
    }
}

fn apply_staged_active_store(
    layout: &DataLayout,
    staged_sqlite: &Path,
    staged_jsonl: &Path,
    audit_entry: &AuditEntry,
) -> Result<ApplyRecoveryEvidence, Exit> {
    let active_parent = layout.db_path.parent().unwrap_or(&layout.data_dir);
    if !active_parent.exists() {
        eprintln!(
            "cortex restore apply-stage: active data directory `{}` does not exist; active store was not changed.",
            active_parent.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    let recovery_dir = active_parent.join(APPLY_RECOVERY_DIR_NAME);
    if recovery_dir.exists() {
        eprintln!(
            "cortex restore apply-stage: recovery evidence directory `{}` already exists; active store was not changed. inspect or remove it before retrying.",
            recovery_dir.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    let tmp_db = layout
        .db_path
        .with_file_name(format!(".cortex.db.apply-stage-{}", std::process::id()));
    let tmp_jsonl = layout
        .event_log_path
        .with_file_name(format!(".events.jsonl.apply-stage-{}", std::process::id()));
    if tmp_db.exists() || tmp_jsonl.exists() {
        eprintln!(
            "cortex restore apply-stage: temporary apply files already exist; active store was not changed."
        );
        return Err(Exit::PreconditionUnmet);
    }
    if let Err(err) = fs::copy(staged_sqlite, &tmp_db) {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        eprintln!(
            "cortex restore apply-stage: failed to prepare staged SQLite copy `{}`: {err}. active store was not changed.",
            tmp_db.display()
        );
        return Err(Exit::Internal);
    }
    if let Err(err) = fs::copy(staged_jsonl, &tmp_jsonl) {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        eprintln!(
            "cortex restore apply-stage: failed to prepare staged JSONL copy `{}`: {err}. active store was not changed.",
            tmp_jsonl.display()
        );
        return Err(Exit::Internal);
    }
    if let Err(exit) = append_restore_command_audit(&tmp_db, audit_entry, "restore apply-stage") {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        return Err(exit);
    }
    let recovery_evidence = match prepare_apply_recovery_evidence(
        layout,
        staged_sqlite,
        staged_jsonl,
        &tmp_db,
        &tmp_jsonl,
    ) {
        Ok(recovery_evidence) => recovery_evidence,
        Err(exit) => {
            cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
            return Err(exit);
        }
    };
    if let Err(err) = fs::rename(&tmp_db, &layout.db_path) {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        eprintln!(
            "cortex restore apply-stage: failed to replace active SQLite store `{}`: {err}. active store was not changed. recovery evidence is available at `{}`.",
            layout.db_path.display(),
            recovery_evidence.manifest_path.display()
        );
        return Err(Exit::Internal);
    }
    if let Err(err) = fs::rename(&tmp_jsonl, &layout.event_log_path) {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        let rollback = restore_current_backups(layout, &recovery_evidence);
        match rollback {
            Ok(()) => {
                eprintln!(
                    "cortex restore apply-stage: failed to replace active JSONL mirror `{}` after SQLite replacement: {err}. active backups were restored; recovery evidence is available at `{}`.",
                    layout.event_log_path.display(),
                    recovery_evidence.manifest_path.display()
                );
                return Err(Exit::Internal);
            }
            Err(rollback_err) => {
                eprintln!(
                    "cortex restore apply-stage: failed to replace active JSONL mirror `{}` after SQLite replacement: {err}. rollback from recovery backups failed: {rollback_err}. active store may be partially mutated; recovery evidence is available at `{}`.",
                    layout.event_log_path.display(),
                    recovery_evidence.manifest_path.display()
                );
                return Err(rollback_err.to_exit());
            }
        }
    }
    Ok(recovery_evidence)
}

fn prepare_apply_recovery_evidence(
    layout: &DataLayout,
    staged_sqlite: &Path,
    staged_jsonl: &Path,
    tmp_db: &Path,
    tmp_jsonl: &Path,
) -> Result<ApplyRecoveryEvidence, Exit> {
    let active_parent = layout.db_path.parent().unwrap_or(&layout.data_dir);
    let recovery_dir = active_parent.join(APPLY_RECOVERY_DIR_NAME);
    fs::create_dir(&recovery_dir).map_err(|err| {
        eprintln!(
            "cortex restore apply-stage: failed to create recovery evidence directory `{}`: {err}. active store was not changed.",
            recovery_dir.display()
        );
        Exit::Internal
    })?;

    let active_db_backup = recovery_dir.join("current.cortex.db");
    let active_event_log_backup = recovery_dir.join("current.events.jsonl");
    if let Err(err) = fs::copy(&layout.db_path, &active_db_backup) {
        cleanup_recovery_dir(&recovery_dir);
        eprintln!(
            "cortex restore apply-stage: failed to back up active SQLite store `{}` to `{}`: {err}. active store was not changed.",
            layout.db_path.display(),
            active_db_backup.display()
        );
        return Err(Exit::Internal);
    }
    if let Err(err) = fs::copy(&layout.event_log_path, &active_event_log_backup) {
        cleanup_recovery_dir(&recovery_dir);
        eprintln!(
            "cortex restore apply-stage: failed to back up active JSONL mirror `{}` to `{}`: {err}. active store was not changed.",
            layout.event_log_path.display(),
            active_event_log_backup.display()
        );
        return Err(Exit::Internal);
    }

    let manifest_path = recovery_dir.join(APPLY_RECOVERY_MANIFEST_NAME);
    // Compute the BLAKE3 digests once so we can both pin them in the
    // serialized recovery manifest AND thread them into the in-memory
    // `ApplyRecoveryEvidence` returned to the apply-stage caller. The
    // in-memory copy is what [`restore_current_backups`] re-verifies after
    // an auto-rollback `fs::copy` (Attack C closure).
    let active_db_backup_blake3 = blake3_file(&active_db_backup, "active_db_backup")?;
    let active_event_log_backup_blake3 =
        blake3_file(&active_event_log_backup, "active_event_log_backup")?;
    let manifest = json!({
        "kind": "cortex_restore_apply_stage_recovery_manifest",
        "schema_version": 1,
        "scope": "temp-test",
        "status": "prepared_before_active_replacement",
        "active": {
            "db": layout.db_path,
            "event_log": layout.event_log_path,
        },
        "active_backups": {
            "db": {
                "path": active_db_backup,
                "size_bytes": fs::metadata(&active_db_backup).map(|m| m.len()).unwrap_or(0),
                "blake3": active_db_backup_blake3,
            },
            "event_log": {
                "path": active_event_log_backup,
                "size_bytes": fs::metadata(&active_event_log_backup).map(|m| m.len()).unwrap_or(0),
                "blake3": active_event_log_backup_blake3,
            },
        },
        "staged": {
            "db": staged_sqlite,
            "event_log": staged_jsonl,
        },
        "temporary_apply": {
            "db": tmp_db,
            "event_log": tmp_jsonl,
        },
        "operator_action": "If apply-stage exits non-zero after active replacement begins, restore active paths from active_backups before continuing temp-test writes.",
    });
    let manifest_bytes = serde_json::to_vec_pretty(&manifest).map_err(|err| {
        cleanup_recovery_dir(&recovery_dir);
        eprintln!(
            "cortex restore apply-stage: failed to serialize recovery manifest `{}`: {err}. active store was not changed.",
            manifest_path.display()
        );
        Exit::Internal
    })?;
    if let Err(err) = fs::write(&manifest_path, manifest_bytes) {
        cleanup_recovery_dir(&recovery_dir);
        eprintln!(
            "cortex restore apply-stage: failed to write recovery manifest `{}`: {err}. active store was not changed.",
            manifest_path.display()
        );
        return Err(Exit::Internal);
    }

    Ok(ApplyRecoveryEvidence {
        manifest_path,
        active_db_backup,
        active_event_log_backup,
        active_db_backup_blake3,
        active_event_log_backup_blake3,
    })
}

/// Restore the pre-cutover backups onto the active store after a failed
/// apply-stage / production-restore mutation.
///
/// **Attack C closure** (Rekor-mandatory rollback path):
/// after each `fs::copy` we re-compute the BLAKE3 of the freshly-written
/// destination file and compare it against the digest the recovery
/// manifest pinned at backup-capture time. A mismatch means either the
/// backup file itself was tampered with between capture and rollback, OR
/// the copy did not produce the expected bytes (e.g. partial copy, racing
/// writer). Either way the rollback path MUST NOT silently land
/// attacker-controlled bytes onto the live store, so this surfaces the
/// stable invariant
/// [`RESTORE_RECOVER_ROLLBACK_BACKUP_DIGEST_MISMATCH_INVARIANT`] and
/// returns [`RestoreCurrentBackupsError::DigestMismatch`] which callers
/// translate to [`Exit::IntegrityFailure`].
pub(super) fn restore_current_backups(
    layout: &DataLayout,
    recovery: &ApplyRecoveryEvidence,
) -> Result<(), RestoreCurrentBackupsError> {
    fs::copy(&recovery.active_db_backup, &layout.db_path)
        .map_err(RestoreCurrentBackupsError::Io)?;
    verify_rollback_backup_digest(
        &layout.db_path,
        &recovery.active_db_backup_blake3,
        "active_db",
    )?;
    fs::copy(&recovery.active_event_log_backup, &layout.event_log_path)
        .map_err(RestoreCurrentBackupsError::Io)?;
    verify_rollback_backup_digest(
        &layout.event_log_path,
        &recovery.active_event_log_backup_blake3,
        "active_event_log",
    )?;
    Ok(())
}

/// Re-verify that the freshly-copied file at `destination` matches the
/// digest that the recovery manifest recorded for the backup source.
///
/// Implements the BLAKE3 re-check half of Attack C closure. The
/// `field_label` shows up in operator-facing diagnostics so the transcript
/// names which leg (SQLite vs JSONL) failed.
fn verify_rollback_backup_digest(
    destination: &Path,
    expected_blake3: &str,
    field_label: &str,
) -> Result<(), RestoreCurrentBackupsError> {
    let observed = blake3_file(destination, field_label)
        .map_err(|_| RestoreCurrentBackupsError::DigestRead)?;
    if observed == expected_blake3 {
        return Ok(());
    }
    eprintln!(
        "cortex restore rollback: {invariant}: {field_label} backup digest mismatch on `{path}`: expected {expected}, observed {observed}. \
         the pre-cutover backup recorded a different BLAKE3 than the file the rollback `fs::copy` produced; \
         refusing to mark the rollback complete. active store may be in a partial state — manual recovery from \
         a verified backup is required before continuing writes.",
        invariant = RESTORE_RECOVER_ROLLBACK_BACKUP_DIGEST_MISMATCH_INVARIANT,
        path = destination.display(),
        expected = expected_blake3,
        observed = observed,
    );
    Err(RestoreCurrentBackupsError::DigestMismatch {
        field: field_label.to_string(),
        expected: expected_blake3.to_string(),
        observed,
    })
}

/// Error type for [`restore_current_backups`].
///
/// Split out so callers can distinguish a transient I/O failure from a
/// digest-mismatch (Attack C). The latter is an integrity failure, not an
/// operator-precondition failure, and exits with [`Exit::IntegrityFailure`].
#[derive(Debug)]
pub(super) enum RestoreCurrentBackupsError {
    /// `fs::copy` itself failed.
    Io(std::io::Error),
    /// The rollback `fs::copy` completed but the freshly-written file's
    /// BLAKE3 did not match the digest the recovery manifest recorded.
    DigestMismatch {
        field: String,
        expected: String,
        observed: String,
    },
    /// `blake3_file` failed to read the just-written rollback destination.
    /// Treated as integrity failure because we cannot prove the rollback
    /// landed the expected bytes.
    DigestRead,
}

impl std::fmt::Display for RestoreCurrentBackupsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(err) => write!(f, "rollback copy failed: {err}"),
            Self::DigestMismatch {
                field,
                expected,
                observed,
            } => {
                let invariant = RESTORE_RECOVER_ROLLBACK_BACKUP_DIGEST_MISMATCH_INVARIANT;
                write!(
                    f,
                    "{invariant}: {field} expected {expected}, observed {observed}",
                )
            }
            Self::DigestRead => {
                write!(f, "rollback destination unreadable for digest re-check")
            }
        }
    }
}

impl std::error::Error for RestoreCurrentBackupsError {}

impl RestoreCurrentBackupsError {
    /// Map a rollback failure to the right CLI exit code. I/O failures on
    /// the rollback copy are operator-actionable preconditions; digest
    /// mismatches (and digest-read failures) are integrity failures.
    pub(super) fn to_exit(&self) -> Exit {
        match self {
            Self::Io(_) => Exit::Internal,
            Self::DigestMismatch { .. } | Self::DigestRead => Exit::IntegrityFailure,
        }
    }
}

fn read_apply_recovery_manifest(path: &Path) -> Result<ApplyRecoveryManifest, Exit> {
    let raw = fs::read_to_string(path).map_err(|err| {
        eprintln!(
            "cortex restore recover-apply: recovery manifest `{}` could not be read: {err}. active store was not changed.",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    let manifest: ApplyRecoveryManifest = serde_json::from_str(&raw).map_err(|err| {
        eprintln!(
            "cortex restore recover-apply: recovery manifest `{}` is malformed: {err}. active store was not changed.",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    if manifest.kind != "cortex_restore_apply_stage_recovery_manifest" {
        eprintln!(
            "cortex restore recover-apply: recovery manifest `{}` has invalid kind `{}`; expected cortex_restore_apply_stage_recovery_manifest. active store was not changed.",
            path.display(),
            manifest.kind
        );
        return Err(Exit::PreconditionUnmet);
    }
    if manifest.schema_version != 1 {
        eprintln!(
            "cortex restore recover-apply: recovery manifest `{}` has schema_version {}; expected schema_version 1. active store was not changed.",
            path.display(),
            manifest.schema_version
        );
        return Err(Exit::SchemaMismatch);
    }
    if manifest.scope != "temp-test" {
        eprintln!(
            "cortex restore recover-apply: recovery manifest `{}` has scope `{}`; expected temp-test. active store was not changed.",
            path.display(),
            manifest.scope
        );
        return Err(Exit::PreconditionUnmet);
    }
    if manifest.status != "prepared_before_active_replacement" {
        eprintln!(
            "cortex restore recover-apply: recovery manifest `{}` has unsupported status `{}`. active store was not changed.",
            path.display(),
            manifest.status
        );
        return Err(Exit::PreconditionUnmet);
    }
    Ok(manifest)
}

fn verify_apply_recovery_scope(manifest: &ApplyRecoveryManifest) -> Result<(), Exit> {
    let Some(active_db_parent) = manifest.active.db.parent() else {
        eprintln!(
            "cortex restore recover-apply: active SQLite path has no parent directory; active store was not changed."
        );
        return Err(Exit::PreconditionUnmet);
    };
    if manifest.active.event_log.parent() != Some(active_db_parent) {
        eprintln!(
            "cortex restore recover-apply: active SQLite and JSONL paths do not share a data directory; active store was not changed."
        );
        return Err(Exit::PreconditionUnmet);
    }
    if !is_temp_test_data_dir(active_db_parent) {
        eprintln!(
            "cortex restore recover-apply: active data directory `{}` is not under the system temp directory; active store was not changed.",
            active_db_parent.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    Ok(())
}

fn verify_apply_recovery_backup(
    manifest_path: &Path,
    field: &str,
    backup: &ApplyRecoveryBackupArtifact,
) -> Result<(), Exit> {
    let manifest_dir = manifest_path.parent().unwrap_or_else(|| Path::new("."));
    let metadata = fs::metadata(&backup.path).map_err(|_| {
        eprintln!(
            "cortex restore recover-apply: recovery manifest `{}` references missing `{field}` artifact `{}`. active store was not changed.",
            manifest_path.display(),
            backup.path.display()
        );
        Exit::PreconditionUnmet
    })?;
    if !metadata.is_file() {
        eprintln!(
            "cortex restore recover-apply: recovery manifest `{}` references non-file `{field}` artifact `{}`. active store was not changed.",
            manifest_path.display(),
            backup.path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    if !path_is_within(&backup.path, manifest_dir) {
        eprintln!(
            "cortex restore recover-apply: `{field}` artifact `{}` is outside the recovery manifest directory. active store was not changed.",
            backup.path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    if metadata.len() != backup.size_bytes {
        eprintln!(
            "cortex restore recover-apply: `{field}` artifact `{}` size mismatch: manifest={}, actual={}. active store was not changed.",
            backup.path.display(),
            backup.size_bytes,
            metadata.len()
        );
        return Err(Exit::QuarantinedInput);
    }
    let actual_blake3 = blake3_file(&backup.path, field)?;
    if backup.blake3 != actual_blake3 {
        eprintln!(
            "cortex restore recover-apply: `{field}` artifact `{}` digest mismatch: manifest={}, actual={}. active store was not changed.",
            backup.path.display(),
            backup.blake3,
            actual_blake3
        );
        return Err(Exit::QuarantinedInput);
    }
    Ok(())
}

fn verify_apply_recovery_targets(manifest: &ApplyRecoveryManifest) -> Result<(), Exit> {
    verify_apply_recovery_target("active SQLite", &manifest.active.db)?;
    verify_apply_recovery_target("active JSONL", &manifest.active.event_log)
}

fn verify_apply_recovery_target(label: &str, path: &Path) -> Result<(), Exit> {
    let Ok(metadata) = fs::symlink_metadata(path) else {
        return Ok(());
    };
    if metadata.file_type().is_symlink() {
        eprintln!(
            "cortex restore recover-apply: {label} path `{}` is a symlink; active store was not changed.",
            path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    if !metadata.file_type().is_file() {
        eprintln!(
            "cortex restore recover-apply: {label} path `{}` is not a regular file; active store was not changed.",
            path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    Ok(())
}

fn restore_apply_recovery_backups(
    manifest: &ApplyRecoveryManifest,
    audit_entry: &AuditEntry,
) -> Result<(), Exit> {
    let tmp_db = manifest
        .active
        .db
        .with_file_name(format!(".cortex.db.recover-apply-{}", std::process::id()));
    let tmp_jsonl = manifest.active.event_log.with_file_name(format!(
        ".events.jsonl.recover-apply-{}",
        std::process::id()
    ));
    if tmp_db.exists() || tmp_jsonl.exists() {
        eprintln!(
            "cortex restore recover-apply: temporary recovery files already exist; active store was not changed."
        );
        return Err(Exit::PreconditionUnmet);
    }
    if let Err(err) = fs::copy(&manifest.active_backups.db.path, &tmp_db) {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        eprintln!(
            "cortex restore recover-apply: failed to prepare active SQLite backup copy `{}`: {err}. active store was not changed.",
            tmp_db.display()
        );
        return Err(Exit::Internal);
    }
    // Attack C closure (post-copy re-verify): the recover-apply path
    // verifies the source backup BLAKE3 in `verify_apply_recovery_backup`
    // before this `fs::copy`. The window between that pre-check and the
    // copy is a TOCTOU surface for a malicious file appearing on the
    // backup path. Re-verify the tmp copy against the same recorded
    // digest so the rollback `fs::copy` cannot silently land tampered
    // bytes. The SQLite leg has a command-audit row appended below, so
    // the digest will diverge from `manifest.active_backups.db.blake3`
    // AFTER append_restore_command_audit — we therefore pin the check
    // here before the audit row is added.
    if let Err(err) = verify_rollback_backup_digest(
        &tmp_db,
        &manifest.active_backups.db.blake3,
        "active_db_backup_copy",
    ) {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        return Err(err.to_exit());
    }
    if let Err(err) = fs::copy(&manifest.active_backups.event_log.path, &tmp_jsonl) {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        eprintln!(
            "cortex restore recover-apply: failed to prepare active JSONL backup copy `{}`: {err}. active store was not changed.",
            tmp_jsonl.display()
        );
        return Err(Exit::Internal);
    }
    if let Err(err) = verify_rollback_backup_digest(
        &tmp_jsonl,
        &manifest.active_backups.event_log.blake3,
        "active_event_log_backup_copy",
    ) {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        return Err(err.to_exit());
    }
    if let Err(exit) = append_restore_command_audit(&tmp_db, audit_entry, "restore recover-apply") {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        return Err(exit);
    }
    if let Err(err) = fs::copy(&tmp_db, &manifest.active.db) {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        eprintln!(
            "cortex restore recover-apply: failed to restore active SQLite backup to `{}`: {err}. active store may require manual recovery from the manifest backups.",
            manifest.active.db.display()
        );
        return Err(Exit::Internal);
    }
    if let Err(err) = fs::copy(&tmp_jsonl, &manifest.active.event_log) {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        eprintln!(
            "cortex restore recover-apply: failed to restore active JSONL backup to `{}`: {err}. active store may require manual recovery from the manifest backups.",
            manifest.active.event_log.display()
        );
        return Err(Exit::Internal);
    }
    // Final re-verify on the freshly-landed JSONL: this leg did not get a
    // command-audit row appended (the audit is in SQLite), so it should
    // still match the manifest's recorded backup digest.
    if let Err(err) = verify_rollback_backup_digest(
        &manifest.active.event_log,
        &manifest.active_backups.event_log.blake3,
        "active_event_log_post_restore",
    ) {
        cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
        return Err(err.to_exit());
    }
    cleanup_temporary_apply(&tmp_db, &tmp_jsonl);
    Ok(())
}

fn restore_apply_stage_audit_entry(
    args: &ApplyStageArgs,
    layout: &DataLayout,
    verified: &VerifiedBackup,
    before_hash: Option<String>,
) -> Result<AuditEntry, Exit> {
    let source_refs_json = json!({
        "manifest": args.manifest,
        "stage_dir": args.stage_dir,
        "active_db": layout.db_path,
        "active_event_log": layout.event_log_path,
        "sqlite_store_blake3": verified.sqlite_store.blake3,
        "jsonl_mirror_blake3": verified.jsonl_mirror.blake3,
        "after_hash_semantics": "verified restored SQLite payload before command audit row append; final active SQLite digest is not self-claimed by the row",
        "scope": "temp-test",
    });
    Ok(AuditEntry {
        id: AuditRecordId::new(),
        operation: RESTORE_APPLY_STAGE_COMMAND_AUDIT_OPERATION.to_string(),
        target_ref: format!("active_store:{}", layout.db_path.display()),
        before_hash,
        after_hash: verified.sqlite_store.blake3.clone(),
        reason: "temp-test restore apply-stage replaced active store after manifest, audit, and semantic guards".to_string(),
        actor_json: json!({"kind": "cli", "command": "restore apply-stage", "scope": "temp-test"}),
        source_refs_json,
        created_at: chrono::Utc::now(),
    })
}

fn restore_recover_apply_audit_entry(
    args: &RecoverApplyArgs,
    manifest: &ApplyRecoveryManifest,
    before_hash: Option<String>,
) -> Result<AuditEntry, Exit> {
    let source_refs_json = json!({
        "manifest": args.manifest,
        "active_db": manifest.active.db,
        "active_event_log": manifest.active.event_log,
        "active_db_backup": manifest.active_backups.db.path,
        "active_event_log_backup": manifest.active_backups.event_log.path,
        "active_db_backup_blake3": manifest.active_backups.db.blake3,
        "active_event_log_backup_blake3": manifest.active_backups.event_log.blake3,
        "after_hash_semantics": "verified recovered SQLite backup payload before command audit row append; final active SQLite digest is not self-claimed by the row",
        "scope": manifest.scope,
    });
    Ok(AuditEntry {
        id: AuditRecordId::new(),
        operation: RESTORE_RECOVER_APPLY_COMMAND_AUDIT_OPERATION.to_string(),
        target_ref: format!("active_store:{}", manifest.active.db.display()),
        before_hash,
        after_hash: manifest.active_backups.db.blake3.clone(),
        reason: "temp-test restore recover-apply restored active backups after recovery manifest verification".to_string(),
        actor_json: json!({"kind": "cli", "command": "restore recover-apply", "scope": manifest.scope}),
        source_refs_json,
        created_at: chrono::Utc::now(),
    })
}

fn append_restore_command_audit(
    db_path: &Path,
    audit_entry: &AuditEntry,
    command: &str,
) -> Result<(), Exit> {
    let pool = cortex_store::Pool::open(db_path).map_err(|err| {
        eprintln!(
            "cortex {command}: failed to open SQLite store `{}` for persisted command audit row: {err}. active store was not changed.",
            db_path.display()
        );
        Exit::PreconditionUnmet
    })?;
    AuditRepo::new(&pool).append(audit_entry).map_err(|err| {
        eprintln!(
            "cortex {command}: failed to append persisted command audit row to `{}`: {err}. active store was not changed.",
            db_path.display()
        );
        Exit::Internal
    })
}

fn path_is_within(path: &Path, parent: &Path) -> bool {
    let Ok(path) = path.canonicalize() else {
        return false;
    };
    let Ok(parent) = parent.canonicalize() else {
        return false;
    };
    path.starts_with(parent)
}

fn audit_verify_staged_jsonl(path: &Path) -> Result<Report, Exit> {
    match verify_chain(path) {
        Ok(report) if report.ok() => Ok(report),
        Ok(report) => {
            for failure in &report.failures {
                eprintln!(
                    "cortex restore stage: copied JSONL audit failure at line {}: {:?}",
                    failure.line, failure.reason
                );
            }
            Err(Exit::IntegrityFailure)
        }
        Err(err) => {
            eprintln!(
                "cortex restore stage: copied JSONL audit verification failed for `{}`: {err}. active store was not changed.",
                path.display()
            );
            Err(map_jsonl_verify_err(&err))
        }
    }
}

fn audit_verify_active_jsonl(path: &Path) -> Result<Report, Exit> {
    match verify_chain(path) {
        Ok(report) if report.ok() => Ok(report),
        Ok(report) => {
            for failure in &report.failures {
                eprintln!(
                    "cortex restore apply-stage: post-restore active JSONL audit failure at line {}: {:?}",
                    failure.line, failure.reason
                );
            }
            Err(Exit::IntegrityFailure)
        }
        Err(err) => {
            eprintln!(
                "cortex restore apply-stage: post-restore active JSONL audit verification failed for `{}`: {err}. recovery evidence may be required before continuing writes.",
                path.display()
            );
            Err(map_jsonl_verify_err(&err))
        }
    }
}

fn audit_report(report: &Report) -> serde_json::Value {
    json!({
        "status": "verified",
        "path": report.path,
        "rows_scanned": report.rows_scanned,
        "failures": report.failures.len(),
    })
}

fn map_jsonl_verify_err(err: &JsonlError) -> Exit {
    match err {
        JsonlError::Decode { .. } | JsonlError::ChainBroken(_) => Exit::ChainCorruption,
        JsonlError::Validation(_) => Exit::PreconditionUnmet,
        JsonlError::Io { .. } | JsonlError::Encode(_) => Exit::Internal,
    }
}

fn map_anchor_verify_err(err: &AnchorVerifyError) -> Exit {
    match err {
        AnchorVerifyError::Jsonl(err) => map_jsonl_verify_err(err),
        AnchorVerifyError::EmptyLedger { .. }
        | AnchorVerifyError::InternalAnchorBuild { .. }
        | AnchorVerifyError::ChainBroken { .. }
        | AnchorVerifyError::Truncated { .. }
        | AnchorVerifyError::MissingPosition { .. }
        | AnchorVerifyError::PositionHashMismatch { .. } => Exit::IntegrityFailure,
    }
}

fn map_anchor_history_verify_err(err: &AnchorHistoryVerifyError) -> Exit {
    match err {
        AnchorHistoryVerifyError::ReadHistory { .. } | AnchorHistoryVerifyError::Parse { .. } => {
            Exit::PreconditionUnmet
        }
        AnchorHistoryVerifyError::Anchor { source, .. } => map_anchor_verify_err(source),
        AnchorHistoryVerifyError::NonMonotonic { .. } => Exit::IntegrityFailure,
    }
}

fn cleanup_temporary_stage(path: &Path) {
    if path.exists() {
        let _ = fs::remove_dir_all(path);
    }
}

fn cleanup_temporary_apply(tmp_db: &Path, tmp_jsonl: &Path) {
    if tmp_db.exists() {
        let _ = fs::remove_file(tmp_db);
    }
    if tmp_jsonl.exists() {
        let _ = fs::remove_file(tmp_jsonl);
    }
}

fn cleanup_recovery_dir(recovery_dir: &Path) {
    if recovery_dir.exists() {
        let _ = fs::remove_dir_all(recovery_dir);
    }
}

fn is_temp_test_data_dir(data_dir: &Path) -> bool {
    let Ok(data_dir) = data_dir.canonicalize() else {
        return false;
    };
    let Ok(temp_dir) = std::env::temp_dir().canonicalize() else {
        return false;
    };
    data_dir.starts_with(temp_dir)
}

fn verify_pre_v2_backup(path: &Path) -> Result<VerifiedBackup, Exit> {
    if !path.is_file() {
        eprintln!(
            "cortex restore verify-backup: backup manifest `{}` was not found; no state was changed.",
            path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }

    let raw = fs::read_to_string(path).map_err(|err| {
        eprintln!(
            "cortex restore verify-backup: backup manifest `{}` could not be read: {err}. no state was changed.",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    let manifest: PreV2BackupManifest = serde_json::from_str(&raw).map_err(|err| {
        eprintln!(
            "cortex restore verify-backup: backup manifest `{}` is malformed: {err}. no state was changed.",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;

    if manifest.kind != "cortex_pre_v2_backup" {
        eprintln!(
            "cortex restore verify-backup: backup manifest `{}` has invalid kind `{}`; expected cortex_pre_v2_backup. no state was changed.",
            path.display(),
            manifest.kind
        );
        return Err(Exit::PreconditionUnmet);
    }
    if manifest.schema_version != 1 {
        eprintln!(
            "cortex restore verify-backup: backup manifest `{}` has schema_version {}; expected pre-v2 schema_version 1. no state was changed.",
            path.display(),
            manifest.schema_version
        );
        return Err(Exit::SchemaMismatch);
    }
    if manifest.tool_version.trim().is_empty() {
        eprintln!(
            "cortex restore verify-backup: backup manifest `{}` has empty `tool_version`. no state was changed.",
            path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    if chrono::DateTime::parse_from_rfc3339(&manifest.backup_timestamp).is_err() {
        eprintln!(
            "cortex restore verify-backup: backup manifest `{}` has invalid `backup_timestamp`; expected RFC3339. no state was changed.",
            path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }

    let sqlite_store = verify_manifest_artifact(
        path,
        "sqlite_store",
        &manifest.sqlite_store,
        manifest.sqlite_store_size_bytes,
        &manifest.sqlite_store_blake3,
    )?;
    let jsonl_mirror = verify_manifest_artifact(
        path,
        "jsonl_mirror",
        &manifest.jsonl_mirror,
        manifest.jsonl_mirror_size_bytes,
        &manifest.jsonl_mirror_blake3,
    )?;

    Ok(VerifiedBackup {
        schema_version: manifest.schema_version,
        sqlite_store,
        jsonl_mirror,
    })
}

fn verify_manifest_artifact(
    manifest_path: &Path,
    field: &'static str,
    artifact: &str,
    expected_size_bytes: u64,
    expected_blake3: &str,
) -> Result<VerifiedArtifact, Exit> {
    validate_manifest_artifact_ref(manifest_path, field, artifact)?;
    let path = manifest_artifact_path(manifest_path, artifact);
    let metadata = fs::metadata(&path).map_err(|_| {
        eprintln!(
            "cortex restore verify-backup: manifest `{}` references missing `{field}` artifact `{}`. no state was changed.",
            manifest_path.display(),
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    if !metadata.is_file() {
        eprintln!(
            "cortex restore verify-backup: manifest `{}` references non-file `{field}` artifact `{}`. no state was changed.",
            manifest_path.display(),
            path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    if metadata.len() != expected_size_bytes {
        eprintln!(
            "cortex restore verify-backup: `{field}` artifact `{}` size mismatch: manifest={}, actual={}. no state was changed.",
            path.display(),
            expected_size_bytes,
            metadata.len()
        );
        return Err(Exit::QuarantinedInput);
    }
    let actual_blake3 = blake3_file(&path, field)?;
    if expected_blake3 != actual_blake3 {
        eprintln!(
            "cortex restore verify-backup: `{field}` artifact `{}` digest mismatch: manifest={}, actual={}. no state was changed.",
            path.display(),
            expected_blake3,
            actual_blake3
        );
        return Err(Exit::QuarantinedInput);
    }

    Ok(VerifiedArtifact {
        manifest_field: field,
        path,
        size_bytes: expected_size_bytes,
        blake3: actual_blake3,
    })
}

fn validate_manifest_artifact_ref(
    manifest_path: &Path,
    field: &str,
    artifact: &str,
) -> Result<(), Exit> {
    if artifact.trim().is_empty() {
        eprintln!(
            "cortex restore verify-backup: backup manifest `{}` has empty `{field}`. no state was changed.",
            manifest_path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    let artifact_path = Path::new(artifact);
    if artifact_path.is_absolute() {
        eprintln!(
            "cortex restore verify-backup: backup manifest `{}` has absolute `{field}` artifact reference `{artifact}`. no state was changed.",
            manifest_path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    if artifact_path
        .components()
        .any(|component| matches!(component, std::path::Component::ParentDir))
    {
        eprintln!(
            "cortex restore verify-backup: backup manifest `{}` has parent-directory `{field}` artifact reference `{artifact}`. no state was changed.",
            manifest_path.display()
        );
        return Err(Exit::PreconditionUnmet);
    }
    Ok(())
}

fn manifest_artifact_path(manifest_path: &Path, artifact: &str) -> PathBuf {
    manifest_path
        .parent()
        .unwrap_or_else(|| Path::new("."))
        .join(artifact)
}

fn blake3_file(path: &Path, field: &str) -> Result<String, Exit> {
    let mut file = File::open(path).map_err(|err| {
        eprintln!(
            "cortex restore verify-backup: failed to open `{field}` artifact {}: {err}. no state was changed.",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    let mut hasher = blake3::Hasher::new();
    let mut buffer = [0_u8; 16 * 1024];
    loop {
        let read = file.read(&mut buffer).map_err(|err| {
            eprintln!(
                "cortex restore verify-backup: failed to read `{field}` artifact {}: {err}. no state was changed.",
                path.display()
            );
            Exit::PreconditionUnmet
        })?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(format!("blake3:{}", hasher.finalize().to_hex()))
}

fn read_semantic_snapshot_source(
    snapshot_path: Option<&Path>,
    store_path: Option<&Path>,
    label: &str,
) -> Result<SemanticSnapshot, Exit> {
    match (snapshot_path, store_path) {
        (Some(path), None) => read_snapshot(path, label),
        (None, Some(path)) => read_store_snapshot(path, label),
        (None, None) => {
            eprintln!(
                "cortex restore semantic-diff: missing {label} source; pass --{label} or --{label}-store. no state was changed."
            );
            Err(Exit::PreconditionUnmet)
        }
        (Some(_), Some(_)) => {
            eprintln!(
                "cortex restore semantic-diff: ambiguous {label} source; pass only one of --{label} or --{label}-store. no state was changed."
            );
            Err(Exit::PreconditionUnmet)
        }
    }
}

fn read_store_snapshot(path: &Path, label: &str) -> Result<SemanticSnapshot, Exit> {
    let pool = open_readonly_store(path, "restore semantic-diff")?;
    semantic_snapshot_from_store(&pool).map_err(|err| {
        eprintln!(
            "cortex restore semantic-diff: failed to extract {label} store snapshot {}: {err}",
            path.display()
        );
        Exit::PreconditionUnmet
    })
}

fn read_snapshot(path: &Path, label: &str) -> Result<SemanticSnapshot, Exit> {
    let file = File::open(path).map_err(|err| {
        eprintln!(
            "cortex restore semantic-diff: failed to open {label} snapshot {}: {err}",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;

    serde_json::from_reader(file).map_err(|err| {
        eprintln!(
            "cortex restore semantic-diff: failed to parse {label} snapshot {}: {err}",
            path.display()
        );
        Exit::QuarantinedInput
    })
}

#[cfg(test)]
mod rollback_digest_tests {
    //! Attack C closure tests
    //! (`docs/reviews/CODE_REVIEW_2026-05-12_post_fd779d7.md`):
    //! after a Rekor-failure-triggered auto-rollback restores the
    //! pre-cutover backup via `fs::copy`, the rollback path MUST
    //! re-compute the freshly-written file's BLAKE3 and refuse with
    //! [`RESTORE_RECOVER_ROLLBACK_BACKUP_DIGEST_MISMATCH_INVARIANT`] if
    //! it does not match the digest the recovery manifest recorded.
    //!
    //! These tests target the unit boundary
    //! ([`verify_rollback_backup_digest`]) so they do not depend on the
    //! larger apply-stage harness and so the assertion structure pins
    //! both the invariant token and the exit-code mapping exactly.
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn write_tempfile(contents: &[u8]) -> NamedTempFile {
        let mut tf = NamedTempFile::new().expect("create tempfile");
        tf.write_all(contents).expect("write tempfile");
        tf.flush().expect("flush tempfile");
        tf
    }

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

    #[test]
    fn verify_rollback_backup_digest_passes_when_bytes_match_manifest() {
        let bytes = b"genuine-backup-bytes-for-the-rollback-path";
        let tf = write_tempfile(bytes);
        let expected = blake3_of(bytes);
        verify_rollback_backup_digest(tf.path(), &expected, "active_db_backup")
            .expect("matching BLAKE3 must pass");
    }

    #[test]
    fn verify_rollback_backup_digest_refuses_when_file_was_tampered() {
        // Attack C: the recovery manifest pinned digest D, but the
        // file the rollback `fs::copy` actually wrote has digest D' (an
        // attacker replaced the backup file between manifest write and
        // rollback). The re-check must surface
        // RESTORE_RECOVER_ROLLBACK_BACKUP_DIGEST_MISMATCH_INVARIANT and
        // map to Exit::IntegrityFailure.
        let genuine = b"the-bytes-the-manifest-recorded";
        let tampered = b"attacker-controlled-bytes-on-rollback-path";
        let tf = write_tempfile(tampered);
        let expected = blake3_of(genuine);
        let err = verify_rollback_backup_digest(tf.path(), &expected, "active_db_backup")
            .expect_err("tampered backup must refuse");
        match &err {
            RestoreCurrentBackupsError::DigestMismatch {
                field,
                expected: e,
                observed,
            } => {
                assert_eq!(field, "active_db_backup");
                assert_eq!(e, &expected);
                assert_eq!(observed, &blake3_of(tampered));
            }
            other => panic!("expected DigestMismatch, got {other:?}"),
        }
        assert_eq!(err.to_exit(), Exit::IntegrityFailure);
        // The Display impl must carry the stable invariant token so
        // operator transcripts pivot on it without having to inspect
        // structured fields.
        let rendered = err.to_string();
        assert!(
            rendered.contains(RESTORE_RECOVER_ROLLBACK_BACKUP_DIGEST_MISMATCH_INVARIANT),
            "Display must surface the stable invariant; got: {rendered}",
        );
    }

    #[test]
    fn restore_current_backups_error_exits_are_well_typed() {
        // Documented contract: digest mismatches map to integrity
        // failure (exit 3), digest-read failures also map to integrity
        // failure (we cannot prove the rollback bytes are correct), and
        // I/O failures during the copy map to internal (exit 64).
        let io_err = RestoreCurrentBackupsError::Io(std::io::Error::other("synthetic"));
        assert_eq!(io_err.to_exit(), Exit::Internal);

        let read_err = RestoreCurrentBackupsError::DigestRead;
        assert_eq!(read_err.to_exit(), Exit::IntegrityFailure);

        let mismatch = RestoreCurrentBackupsError::DigestMismatch {
            field: "active_db_backup".to_string(),
            expected: "blake3:aa".to_string(),
            observed: "blake3:bb".to_string(),
        };
        assert_eq!(mismatch.to_exit(), Exit::IntegrityFailure);
    }
}