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
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
//! `cortex audit verify` — operator-facing audit pass over the JSONL log.
//!
//! Wraps [`cortex_ledger::verify_chain`] by default, or
//! [`cortex_ledger::verify_signed_chain`] when `--signed --verification-key`
//! (or the local development `--attestation` seed path) is requested, then
//! translates the typed [`Report`] into the CLI's exit-code
//! table:
//!
//! | Outcome                              | Exit                               |
//! |--------------------------------------|------------------------------------|
//! | `Ok(Report)` with `failures.is_empty()` | [`Exit::Ok`]                       |
//! | `Ok(Report)` with `failures.len() > 0`  | [`Exit::IntegrityFailure`] (`3`)   |
//! | `Err(JsonlError::Decode\|Io\|..)`        | [`Exit::ChainCorruption`] (`6`)    |
//!
//! The split is the BUILD_SPEC §11 contract: per-row chain breaks (orphan,
//! payload-hash mismatch, event-hash mismatch, ordinal gap, signed-chain
//! verification failure) are
//! `IntegrityFailure`; a file that does not parse as JSONL at all (truncated
//! line, byte-flip in the middle of a value) is `ChainCorruption`. Both are
//! actionable by an operator, but they call for different recovery paths
//! (re-derive missing rows vs. restore from mirror).

use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;

use chrono::{DateTime, Utc};
use clap::{Args, Subcommand, ValueEnum};
use cortex_core::{
    compose_policy_outcomes, Attestor, AuthorityClass, ClaimCeiling, ClaimProofState, FailingEdge,
    InMemoryAttestor, PolicyContribution, PolicyDecision, PolicyOutcome, ProofClosureReport,
    ProofEdge, ProofEdgeFailure, ProofEdgeKind, RuntimeMode,
};
use cortex_ledger::{
    anchor::{verify_anchor_history, AnchorHistoryVerifyError},
    audit::verify_schema_migration_v1_to_v2_boundary,
    current_anchor, enforce_disjoint_authority_quorum, parse_anchor, rekor_submit,
    rekor_verify_receipt, verify_anchor, verify_chain, verify_signed_chain, AnchorVerifyError,
    ExternalReceipt, ExternalReceiptVerifyError, ExternalSink, JsonlError, JsonlLog, OtsWitness,
    RekorError, Report, TrustRootStalenessAnchor, TrustedRoot, ANCHOR_TEXT_HASH_MISMATCH_INVARIANT,
    OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT, PARSED_ONLY_VERIFICATION_STATUS,
    REKOR_DEFAULT_ENDPOINT, REKOR_EXTERNAL_AUTHORITY_STATUS, REKOR_SUBMIT_FAILED_INVARIANT,
    REKOR_TRUSTED_ROOT_STALE_INVARIANT, REKOR_VERIFY_FAILED_INVARIANT,
    REKOR_VERIFY_SIGNATURE_MISMATCH_INVARIANT,
};
use cortex_runtime::{
    development_ledger_use_decision, runtime_claim_preflight, runtime_claim_preflight_with_policy,
    DevelopmentLedgerUse, RuntimeClaimKind,
};
use cortex_verifier::SelfSignedKeyRegistry;
use ed25519_dalek::VerifyingKey;
use serde::Serialize;

// =============================================================================
// ADR 0026 rule ids — `cortex audit` policy composition (punch list #20 / #21)
// =============================================================================

/// `cortex audit verify` — hash-chain closure contributor (ADR 0021 / 0022).
pub const VERIFY_HASH_CHAIN_CLOSURE_RULE_ID: &str = "audit.verify.hash_chain_closure";
/// `cortex audit verify` — signed-chain closure contributor (ADR 0010 / 0022).
pub const VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID: &str = "audit.verify.signed_chain_closure";
/// `cortex audit verify` — schema v1→v2 boundary contributor (ADR 0027 / 0035).
pub const VERIFY_V1_TO_V2_BOUNDARY_RULE_ID: &str = "audit.verify.v1_to_v2_boundary";
/// `cortex audit verify` — composed cross-axis proof closure report (ADR 0036).
///
/// Stable invariant key. Folds the three per-axis contributors
/// ([`VERIFY_HASH_CHAIN_CLOSURE_RULE_ID`],
/// [`VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID`],
/// [`VERIFY_V1_TO_V2_BOUNDARY_RULE_ID`]) into a single typed
/// [`ProofClosureReport`] so a consumer can read off the ADR 0036
/// three-valued result for the verify pass as a whole. The composition rule
/// is: hash-chain Reject collapses the whole report to `Broken`; otherwise
/// the weakest truthful state is taken across the surviving axis edges.
pub const VERIFY_PROOF_CLOSURE_COMPOSED_REPORT_INVARIANT: &str =
    "audit.verify.proof_closure.composed_report";
/// `cortex audit verify --signed` — operator temporal authority contributor
/// (ADR 0023 / ADR 0019). Phase 2.6 closure
/// (`docs/design/PHASE_2_6_temporal_authority_revalidation_audit.md`):
/// `verify_signed_chain` is purely Ed25519, so the temporal axis must be
/// observed via [`cortex_store::repo::AuthorityRepo::revalidate`] against
/// the durable timeline.
pub const VERIFY_TEMPORAL_AUTHORITY_RULE_ID: &str = "audit.verify.temporal_authority";
/// `cortex audit anchor` — sink authority contributor (ADR 0013).
pub const ANCHOR_SINK_AUTHORITY_RULE_ID: &str = "audit.anchor.sink_authority";
/// `cortex audit anchor` — operator temporal authority contributor (ADR 0023
/// / ADR 0019). Phase 2.6 T3 closure
/// (`docs/design/PHASE_2_6_temporal_authority_revalidation_audit.md`):
/// anchoring publishes a tip outside the local boundary, so any
/// signed-row `key_id` aggregated across the rows the anchor covers must
/// be revalidated against the durable timeline via
/// [`cortex_store::repo::AuthorityRepo::revalidate`].
pub const ANCHOR_TEMPORAL_AUTHORITY_RULE_ID: &str = "audit.anchor.temporal_authority";
/// `cortex audit export` — development-ledger forbidden-use contributor
/// (ADR 0035 / 0037).
pub const EXPORT_DEVELOPMENT_LEDGER_RULE_ID: &str = "audit.export.development_ledger";
/// `cortex audit export` — signed-local class contributor (ADR 0037 §4).
pub const EXPORT_SIGNED_LOCAL_CLASS_RULE_ID: &str = "audit.export.signed_local_class";
/// `cortex audit export` — proof closure contributor (ADR 0036).
pub const EXPORT_PROOF_CLOSURE_RULE_ID: &str = "audit.export.proof_closure";
/// `cortex audit export` — operator temporal authority contributor
/// (ADR 0023 / ADR 0019). Phase 2.6 T3 closure
/// (`docs/design/PHASE_2_6_temporal_authority_revalidation_audit.md`):
/// the export bridge into compliance / cross-system / external-reporting
/// surfaces requires the per-row `key_id` to be revalidated against the
/// durable timeline before any artifact is emitted.
pub const EXPORT_TEMPORAL_AUTHORITY_RULE_ID: &str = "audit.export.temporal_authority";

use crate::cmd::open_default_store;
use crate::cmd::temporal::{revalidate_operator_temporal_authority, revalidation_failed_invariant};
use crate::exit::Exit;
use crate::output::{self, Envelope};
use crate::paths::DataLayout;
use cortex_core::TrustTier;

/// `cortex audit ...` subcommands.
#[derive(Debug, Subcommand)]
pub enum AuditSub {
    /// Verify the JSONL hash chain end-to-end and report any failures.
    Verify(VerifyArgs),

    /// Emit or append the current position-bound ledger anchor.
    Anchor(AnchorArgs),

    /// Export a conservative audit artifact.
    Export(ExportArgs),

    /// Refresh the cached Sigstore `trusted_root.json` used by the
    /// external-anchor receipt verifier.
    ///
    /// Council Decision #1 (TUF-rooted Rekor trust bundle). Fetches the
    /// current `trusted_root.json` from a TUF mirror (default Sigstore
    /// CDN), structurally validates the payload against the embedded
    /// snapshot's schema, and atomically installs it at the cache path.
    /// Operators must rerun this periodically (the verify path refuses
    /// to mark anchor authority authoritative when a cached root has
    /// aged past 30 days).
    #[command(name = "refresh-trust")]
    RefreshTrust(RefreshTrustArgs),
}

/// `cortex audit verify` flags.
#[derive(Debug, Args)]
pub struct VerifyArgs {
    /// Override the JSONL event-log path. Defaults to the layout-resolved
    /// path (same default as `cortex init`).
    #[arg(long = "event-log", value_name = "PATH")]
    pub event_log: Option<PathBuf>,

    /// Override the SQLite DB path; carried through for layout symmetry.
    #[arg(long, value_name = "PATH")]
    pub db: Option<PathBuf>,

    /// Verify the Ed25519 signed ledger chain instead of hash-chain mechanics only.
    #[arg(long)]
    pub signed: bool,

    /// 32-byte Ed25519 public key used to verify the signed ledger chain.
    #[arg(long = "verification-key", value_name = "KEY_PATH")]
    pub verification_key: Option<PathBuf>,

    /// 32-byte Ed25519 seed used to verify the signed ledger chain.
    ///
    /// Retained for local development compatibility. Prefer
    /// `--verification-key` when verification should not handle signing
    /// authority.
    #[arg(long, value_name = "KEY_PATH")]
    pub attestation: Option<PathBuf>,

    /// Require exactly one `schema_migration.v1_to_v2` boundary row.
    #[arg(long = "require-v1-to-v2-boundary")]
    pub require_v1_to_v2_boundary: bool,

    /// Verify against a v1 position-bound ledger anchor file.
    #[arg(long = "against", value_name = "ANCHOR_PATH")]
    pub against: Option<PathBuf>,

    /// Verify against a monotonic v1 position-bound ledger anchor history.
    #[arg(long = "against-history", value_name = "ANCHOR_HISTORY_PATH")]
    pub against_history: Option<PathBuf>,

    /// Verify against a monotonic v1 external anchor receipt history.
    ///
    /// Parser-only today: recomputes `anchor_text_sha256` from the local
    /// ledger and confirms the receipt-declared
    /// `(anchor_event_count, anchor_chain_head_hash)` pair via the
    /// existing position-bound anchor verifier. The Rekor
    /// `SignedEntryTimestamp` signature and OpenTimestamps `.ots` proof
    /// are NOT yet verified — see
    /// `docs/design/DESIGN_external_anchor_authority.md` §Residual risk.
    /// Successful verification reports
    /// `external_anchor_authority=parsed_only_signature_verification_pending`.
    #[arg(long = "against-external", value_name = "RECEIPTS_PATH")]
    pub against_external: Option<PathBuf>,

    /// Path to a TOML file containing operator self-signed public keys.
    ///
    /// Required when the witness set includes `SelfSigned` witnesses. Without
    /// this flag, any `SelfSigned` witness fails closed with
    /// `verifier.witness.signature_invalid`.
    ///
    /// File format (TOML):
    ///
    /// ```toml
    /// [[keys]]
    /// key_id = "my-operator-key"
    /// algorithm = "ed25519"
    /// key_bytes_hex = "aabbcc..."  # 64 hex chars for Ed25519 (32 bytes)
    /// ```
    #[arg(long = "witness-key-registry", value_name = "PATH")]
    pub witness_key_registry: Option<PathBuf>,
}

/// `cortex audit anchor` flags.
#[derive(Debug, Args)]
pub struct AnchorArgs {
    /// Override the JSONL event-log path. Defaults to the layout-resolved
    /// path (same default as `cortex init`).
    #[arg(long = "event-log", value_name = "PATH")]
    pub event_log: Option<PathBuf>,

    /// Override the SQLite DB path; carried through for layout symmetry.
    #[arg(long, value_name = "PATH")]
    pub db: Option<PathBuf>,

    /// Write a single canonical anchor file. Fails if the output already exists.
    #[arg(long, value_name = "PATH")]
    pub output: Option<PathBuf>,

    /// Append the canonical anchor to a local anchor-history sink after verifying existing history.
    #[arg(long, value_name = "PATH")]
    pub history: Option<PathBuf>,

    /// Authority sink selected for this anchor publication.
    ///
    /// `local-only` emits or writes local weak-mode evidence.
    /// `external-append-only` is reserved for a future configured disjoint
    /// sink and fails closed today. `rekor` and `opentimestamps` are the
    /// adapter slots for the ADR 0013 Mechanism C foundation; both
    /// currently fail closed with a stable
    /// `external_sink_adapter_not_yet_implemented_pending_design_specs`
    /// reason because the live submission and verification adapters wait
    /// on operator decisions (Rekor public key pin, ECDSA-P-256 vs Ed25519
    /// for `SignedEntryTimestamp`, OTS binary proof format) — see
    /// `docs/design/DESIGN_external_anchor_authority.md` §Residual risk.
    #[arg(long, value_enum, default_value = "local-only")]
    pub sink: AnchorSink,

    /// Configured external sink path candidate.
    ///
    /// A normal local path is not enough to prove disjoint append-only semantics,
    /// so this currently fails closed instead of writing an anchor.
    #[arg(long = "sink-path", value_name = "PATH")]
    pub sink_path: Option<PathBuf>,

    /// Network endpoint for the external sink adapter
    /// (e.g. `https://rekor.sigstore.dev`).
    ///
    /// Accepted by the parser today but unused — the adapter that would
    /// consume it is deferred. Surfacing the flag now lets operators wire
    /// scripts without depending on its semantics changing later.
    #[arg(long = "sink-endpoint", value_name = "URL")]
    pub sink_endpoint: Option<String>,

    /// Output path for a single v1 external anchor receipt sidecar.
    ///
    /// Mirrors `--output` for `external-*` sinks. Parsed but unused until
    /// the submission adapter lands.
    #[arg(long = "sink-receipt", value_name = "PATH")]
    pub sink_receipt: Option<PathBuf>,

    /// Append-only path for the v1 external anchor receipt history.
    ///
    /// Mirrors `--history` for `external-*` sinks. Parsed but unused until
    /// the submission adapter lands.
    #[arg(long = "sink-receipt-history", value_name = "PATH")]
    pub sink_receipt_history: Option<PathBuf>,

    /// Refuse to make any network call against the external sink.
    ///
    /// Reserved for the future verify-from-cache flow. Parsed today so
    /// scripts can pin the intended semantics ahead of the adapter
    /// landing.
    #[arg(long = "offline")]
    pub offline: bool,

    /// `--sink opentimestamps` only: explicitly require a non-Pending
    /// receipt. This is the **default** behavior — operator decision
    /// #3 maps Pending to `Reject` for the strong-mode anchor surface
    /// — so the flag is for script-level explicitness rather than to
    /// change the default. Mutually exclusive with `--allow-pending`.
    #[arg(long = "require-non-pending", conflicts_with = "allow_pending")]
    pub require_non_pending: bool,

    /// `--sink opentimestamps` only: lower the bar so Pending receipts
    /// produce a Quarantine outcome with
    /// `external_authority_opentimestamps_pending` rather than a hard
    /// Reject. Mutually exclusive with `--require-non-pending`.
    #[arg(long = "allow-pending")]
    pub allow_pending: bool,

    /// `--sink opentimestamps` only: path to a pre-fetched `.ots`
    /// proof file. When supplied, the CLI does NOT contact the
    /// calendar; it parses the bytes through the trait wrapper and
    /// emits the receipt as if the calendar had returned them. The
    /// drill script uses this to exercise the policy lattice without
    /// needing a live calendar.
    #[arg(long = "sink-receipt-in", value_name = "PATH")]
    pub sink_receipt_in: Option<PathBuf>,

    /// `--sink opentimestamps` only: path to an operator-supplied
    /// Bitcoin block header (80 raw bytes) referenced by the
    /// `BitcoinConfirmed` attestation in the receipt. Required to
    /// promote a `BitcoinConfirmed` proof from Partial to
    /// FullChainVerified. Without it the adapter records the
    /// `ots.bitcoin_confirmed.block_header_mismatch` invariant.
    #[arg(long = "bitcoin-header", value_name = "PATH")]
    pub bitcoin_header: Option<PathBuf>,
}

/// Anchor sink authority selected by `cortex audit anchor`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum AnchorSink {
    /// Local stdout, output file, or local history evidence only.
    LocalOnly,
    /// Future disjoint append-only sink. Fails closed until configured.
    ExternalAppendOnly,
    /// Sigstore Rekor public transparency log. Adapter not yet implemented.
    Rekor,
    /// OpenTimestamps Bitcoin-rooted calendar proof. Adapter not yet implemented.
    #[value(name = "opentimestamps", alias = "open-timestamps")]
    OpenTimestamps,
}

impl AnchorSink {
    const fn authority_label(self) -> &'static str {
        match self {
            Self::LocalOnly => "local_only",
            Self::Rekor => "external_authority_rekor",
            Self::ExternalAppendOnly | Self::OpenTimestamps => "external_unconfigured",
        }
    }

    const fn external_configured(self) -> bool {
        match self {
            Self::LocalOnly | Self::ExternalAppendOnly | Self::OpenTimestamps => false,
            Self::Rekor => true,
        }
    }

    const fn external_authority(self) -> bool {
        match self {
            Self::LocalOnly | Self::ExternalAppendOnly | Self::OpenTimestamps => false,
            Self::Rekor => true,
        }
    }

    /// Stable wire token used in CLI diagnostic messages.
    const fn wire_str(self) -> &'static str {
        match self {
            Self::LocalOnly => "local-only",
            Self::ExternalAppendOnly => "external-append-only",
            Self::Rekor => "rekor",
            Self::OpenTimestamps => "opentimestamps",
        }
    }
}

/// Stable machine-readable reason emitted when an operator selects a
/// network-bound external sink whose live adapter has not yet been
/// implemented. The string is part of the CLI contract; downstream
/// scripts grep for this exact token to differentiate "adapter not
/// implemented" from "external sink misconfigured".
pub const EXTERNAL_SINK_ADAPTER_NOT_YET_IMPLEMENTED_REASON: &str =
    "external_sink_adapter_not_yet_implemented_pending_design_specs";

/// Authority label for an OTS receipt whose Bitcoin attestation
/// cross-checked successfully — strong-mode authority unlocked.
pub const EXTERNAL_AUTHORITY_OPENTIMESTAMPS: &str = "external_authority_opentimestamps";

/// Authority label for an OTS receipt accepted under `--allow-pending`
/// (Quarantine outcome — operator opted into a weaker bar while waiting
/// for the Bitcoin confirmation).
pub const EXTERNAL_AUTHORITY_OPENTIMESTAMPS_PENDING: &str =
    "external_authority_opentimestamps_pending";

/// Stable reason emitted when the OTS adapter rejects a Pending receipt
/// under the default `--require-non-pending` policy. Downstream scripts
/// grep for this token to distinguish "calendar refused" from
/// "still waiting for Bitcoin confirmation".
pub const OTS_PENDING_REJECTED_UNDER_REQUIRE_NON_PENDING_REASON: &str =
    "ots_pending_rejected_under_require_non_pending";

/// Stable reason emitted when the OTS adapter accepts a Pending receipt
/// under `--allow-pending`. Pairs with
/// [`EXTERNAL_AUTHORITY_OPENTIMESTAMPS_PENDING`].
pub const OTS_PENDING_ACCEPTED_UNDER_ALLOW_PENDING_REASON: &str =
    "ots_pending_accepted_under_allow_pending";

/// Stable reason emitted when a `BitcoinConfirmed` proof was accepted
/// and its merkle-root cross-check against the operator-supplied
/// Bitcoin block header succeeded.
pub const OTS_BITCOIN_CONFIRMED_VERIFIED_REASON: &str = "ots_bitcoin_confirmed_verified";

struct AnchorSinkDecision {
    authority_label: &'static str,
    external_configured: bool,
    external_authority: bool,
    reason: &'static str,
    /// ADR 0026 outcome for the `audit.anchor.sink_authority` contributor.
    /// Composes uniformly with the rest of the policy lattice instead of
    /// being a bespoke sink-decision table.
    policy_outcome: PolicyOutcome,
}

fn anchor_sink_decision(sink: AnchorSink, sink_path: Option<&PathBuf>) -> AnchorSinkDecision {
    match (sink, sink_path) {
        (AnchorSink::LocalOnly, None) => AnchorSinkDecision {
            authority_label: sink.authority_label(),
            external_configured: sink.external_configured(),
            external_authority: sink.external_authority(),
            reason: "local_only",
            // Local-only sink is the canonical happy path for ADR 0013
            // weak-mode anchor publication. Compose `Allow` and rely on
            // `forbidden_uses` in the report to enforce the truth ceiling
            // — an `Allow` here MUST NOT launder local evidence into
            // compliance / cross-system trust authority.
            policy_outcome: PolicyOutcome::Allow,
        },
        (AnchorSink::LocalOnly, Some(_)) => AnchorSinkDecision {
            authority_label: "local_only",
            external_configured: true,
            external_authority: false,
            reason: "sink_path_requires_external_append_only_sink",
            // The CLI flag combination is invalid; fail closed at the
            // contributor level so the policy view agrees with the
            // existing `Exit::Usage` mapping.
            policy_outcome: PolicyOutcome::Reject,
        },
        (AnchorSink::ExternalAppendOnly, None) => AnchorSinkDecision {
            authority_label: "external_unconfigured",
            external_configured: false,
            external_authority: false,
            reason: "missing_external_sink_path",
            // No disjoint sink configured: ADR 0013 says external claims
            // are not possible. Fail closed.
            policy_outcome: PolicyOutcome::Reject,
        },
        (AnchorSink::ExternalAppendOnly, Some(_)) => AnchorSinkDecision {
            authority_label: "external_path_unproven",
            external_configured: true,
            external_authority: false,
            reason: "local_path_cannot_prove_disjoint_append_only_semantics",
            // A local-disk path cannot prove disjoint authority. ADR 0026
            // §3 says this is exactly the "Quarantine" case: forensic
            // value exists (we know the operator attempted external
            // publication), but the artifact must not be used as
            // canonical external evidence.
            policy_outcome: PolicyOutcome::Quarantine,
        },
        // Rekor moved from parser-only to live submit + verify in slice
        // 2 of Gate 4. The actual sink decision is now produced by
        // `rekor_anchor_sink_decision` after the network round-trip
        // succeeds (or fails). This match arm returns a placeholder
        // Quarantine outcome so the structural error paths above still
        // type-check; the real decision is rewritten downstream.
        (AnchorSink::Rekor, _) => AnchorSinkDecision {
            authority_label: sink.authority_label(),
            external_configured: true,
            external_authority: false,
            reason: "rekor_live_adapter_pending_submit",
            policy_outcome: PolicyOutcome::Quarantine,
        },
        // OpenTimestamps falls through to live `run_anchor_inner` with
        // a placeholder decision below. The live adapter (Gate 4)
        // overwrites this default with the real `AnchorSinkDecision`
        // before reporting — see `ots_anchor_sink_decision`.
        (AnchorSink::OpenTimestamps, _) => AnchorSinkDecision {
            authority_label: "external_unconfigured",
            external_configured: false,
            external_authority: false,
            reason: "ots_live_adapter_invoked_pending_real_outcome",
            policy_outcome: PolicyOutcome::Quarantine,
        },
    }
}

/// Compose the OpenTimestamps-specific anchor decision based on the
/// live adapter's verification outcome and the operator flags. This is
/// the policy lattice for operator decision #3 (Pending → Reject
/// unless `--allow-pending`, BitcoinConfirmed → Allow when the
/// block-header cross-check succeeds).
fn ots_anchor_sink_decision(
    outcome: &cortex_ledger::OtsVerificationOutcome,
    allow_pending: bool,
) -> AnchorSinkDecision {
    use cortex_ledger::OtsVerificationOutcome;
    match outcome {
        OtsVerificationOutcome::FullChainVerified { .. } => AnchorSinkDecision {
            authority_label: EXTERNAL_AUTHORITY_OPENTIMESTAMPS,
            external_configured: true,
            external_authority: true,
            reason: OTS_BITCOIN_CONFIRMED_VERIFIED_REASON,
            // The Bitcoin block-header cross-check unlocks ADR 0013
            // strong-mode authority for the OTS witness.
            policy_outcome: PolicyOutcome::Allow,
        },
        OtsVerificationOutcome::Partial { reasons, .. } => {
            // The Partial branch is the Pending path AND the "Bitcoin
            // attestation present but no header source supplied" path.
            // Both reasons carry their stable invariant; we lower-case
            // the comparison so the wire token stays a single source
            // of truth.
            let is_pending = reasons
                .iter()
                .any(|r| r == cortex_ledger::OTS_PENDING_NO_BITCOIN_ATTESTATION_YET_INVARIANT);
            if is_pending {
                if allow_pending {
                    AnchorSinkDecision {
                        authority_label: EXTERNAL_AUTHORITY_OPENTIMESTAMPS_PENDING,
                        external_configured: true,
                        external_authority: false,
                        reason: OTS_PENDING_ACCEPTED_UNDER_ALLOW_PENDING_REASON,
                        // `--allow-pending` lowers the bar — operator
                        // opted in to quarantine semantics: forensic
                        // value with no strong-mode authority claim.
                        policy_outcome: PolicyOutcome::Quarantine,
                    }
                } else {
                    AnchorSinkDecision {
                        authority_label: "external_unconfigured",
                        external_configured: true,
                        external_authority: false,
                        reason: OTS_PENDING_REJECTED_UNDER_REQUIRE_NON_PENDING_REASON,
                        policy_outcome: PolicyOutcome::Reject,
                    }
                }
            } else {
                // Bitcoin attestation present but no header source —
                // also a Quarantine outcome, regardless of pending flags.
                AnchorSinkDecision {
                    authority_label: EXTERNAL_AUTHORITY_OPENTIMESTAMPS_PENDING,
                    external_configured: true,
                    external_authority: false,
                    reason: cortex_ledger::OTS_BITCOIN_CONFIRMED_BLOCK_HEADER_MISMATCH_INVARIANT,
                    policy_outcome: PolicyOutcome::Quarantine,
                }
            }
        }
        OtsVerificationOutcome::Broken { edge, .. } => AnchorSinkDecision {
            authority_label: "external_unconfigured",
            external_configured: true,
            external_authority: false,
            reason: edge.invariant,
            // A broken merkle path is a hard fail-closed integrity
            // failure; the operator MUST NOT promote this receipt.
            policy_outcome: PolicyOutcome::Reject,
        },
    }
}

/// Build the [`AnchorSinkDecision`] emitted by the live Rekor adapter
/// after submit + verify completes. The outcome lattice mirrors ADR 0026
/// §3:
///
/// - `Allow` when submit + verify succeed and the trust root is fresh.
/// - `Quarantine` when the trust root is older than the 30-day staleness
///   window (operator must refresh before strong claims).
/// - `Reject` on any submit failure, verify failure, or malformed
///   receipt.
fn rekor_anchor_sink_decision(outcome: &RekorAdapterOutcome) -> AnchorSinkDecision {
    match outcome {
        RekorAdapterOutcome::Allowed => AnchorSinkDecision {
            authority_label: "external_authority_rekor",
            external_configured: true,
            external_authority: true,
            reason: REKOR_EXTERNAL_AUTHORITY_STATUS,
            policy_outcome: PolicyOutcome::Allow,
        },
        RekorAdapterOutcome::QuarantineTrustedRootStale => AnchorSinkDecision {
            authority_label: "external_authority_rekor_quarantined",
            external_configured: true,
            external_authority: false,
            reason: REKOR_TRUSTED_ROOT_STALE_INVARIANT,
            policy_outcome: PolicyOutcome::Quarantine,
        },
        RekorAdapterOutcome::Rejected { invariant, .. } => AnchorSinkDecision {
            authority_label: "external_authority_rekor_rejected",
            external_configured: true,
            external_authority: false,
            reason: invariant,
            policy_outcome: PolicyOutcome::Reject,
        },
    }
}

/// Result of a `cortex audit anchor --sink rekor` live submit + verify
/// pass. Carried out of the adapter so the CLI can emit a stable
/// machine-readable report and compose ADR 0026 outcomes uniformly.
///
/// The composition lattice only needs to know which arm fired; the
/// actual receipt / verification / signed_at values are held by local
/// variables in `run_anchor_rekor` so they can flow into the JSON
/// envelope.
#[derive(Debug)]
enum RekorAdapterOutcome {
    /// Submit + verify succeeded against a fresh trust root.
    Allowed,
    /// Submit + verify succeeded but the trust root is older than the
    /// 30-day staleness window.
    QuarantineTrustedRootStale,
    /// Submit or verify failed. `invariant` is the stable token to log.
    Rejected {
        invariant: &'static str,
        #[allow(dead_code)]
        reason: String,
    },
}

/// `cortex audit export` flags.
#[derive(Debug, Args)]
pub struct ExportArgs {
    /// Override the JSONL event-log path. Defaults to the layout-resolved
    /// path (same default as `cortex init`).
    #[arg(long = "event-log", value_name = "PATH")]
    pub event_log: Option<PathBuf>,

    /// Override the SQLite DB path; carried through for layout symmetry.
    #[arg(long, value_name = "PATH")]
    pub db: Option<PathBuf>,

    /// Permit a local diagnostic artifact for development-ledger rows.
    #[arg(long = "local-diagnostic")]
    pub local_diagnostic: bool,

    /// Authority surface requested from the audit export path.
    #[arg(long, value_enum, default_value = "audit-export")]
    pub surface: AuditExportSurface,
}

/// Conservative authority surfaces available through `cortex audit export`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum AuditExportSurface {
    /// Existing audit export surface.
    AuditExport,
    /// Compliance evidence surface.
    ComplianceEvidence,
    /// Cross-system trust decision surface.
    CrossSystemTrustDecision,
    /// External reporting surface.
    ExternalReporting,
}

impl AuditExportSurface {
    const fn label(self) -> &'static str {
        match self {
            Self::AuditExport => "audit export",
            Self::ComplianceEvidence => "compliance evidence",
            Self::CrossSystemTrustDecision => "cross-system trust decision",
            Self::ExternalReporting => "external reporting",
        }
    }

    const fn artifact_kind(self) -> &'static str {
        match self {
            Self::AuditExport => "audit_summary",
            Self::ComplianceEvidence => "compliance_evidence",
            Self::CrossSystemTrustDecision => "cross_system_trust_decision",
            Self::ExternalReporting => "external_reporting",
        }
    }

    const fn development_ledger_use(self) -> DevelopmentLedgerUse {
        match self {
            Self::AuditExport => DevelopmentLedgerUse::AuditExport,
            Self::ComplianceEvidence => DevelopmentLedgerUse::ComplianceEvidence,
            Self::CrossSystemTrustDecision => DevelopmentLedgerUse::CrossSystemTrustDecision,
            Self::ExternalReporting => DevelopmentLedgerUse::ExternalReporting,
        }
    }

    const fn runtime_claim_kind(self) -> RuntimeClaimKind {
        match self {
            Self::AuditExport | Self::ExternalReporting => RuntimeClaimKind::Export,
            Self::ComplianceEvidence => RuntimeClaimKind::ComplianceEvidence,
            Self::CrossSystemTrustDecision => RuntimeClaimKind::CrossSystemTrust,
        }
    }

    const fn requested_ceiling(self) -> ClaimCeiling {
        match self {
            Self::AuditExport | Self::ExternalReporting => ClaimCeiling::ExternallyAnchored,
            Self::ComplianceEvidence | Self::CrossSystemTrustDecision => {
                ClaimCeiling::AuthorityGrade
            }
        }
    }

    const fn is_default_audit_export(self) -> bool {
        matches!(self, Self::AuditExport)
    }
}

/// Top-level dispatcher.
pub fn run(sub: AuditSub) -> Exit {
    match sub {
        AuditSub::Verify(args) => run_verify(args),
        AuditSub::Anchor(args) => run_anchor(args),
        AuditSub::Export(args) => run_export(args),
        AuditSub::RefreshTrust(args) => run_refresh_trust(args),
    }
}

/// Run `cortex audit verify`. Returns the CLI exit code.
///
/// Phase 2.6 closure: when the composed `cortex audit verify`
/// [`PolicyDecision`] is `Reject` or `Quarantine` (e.g. because the
/// `audit.verify.temporal_authority` contributor refused the durable
/// timeline revalidation), the surface MUST fail closed even when the
/// inner chain walk returned `Exit::Ok`. ADR 0026 §2 weakest-link
/// composition forbids a `Reject` axis from being silenced by an
/// `Allow` peer; ADR 0036 §3 states `BROKEN(edge)` once any required
/// axis fails. Returning `Exit::Ok` here would invert both rules.
pub fn run_verify(args: VerifyArgs) -> Exit {
    VERIFY_CONTRIBUTIONS.with(|cell| cell.borrow_mut().clear());
    let inner_exit = run_verify_inner(args);
    let (policy, proof_closure) = compose_verify_policy_decision();
    record_verify_policy_decision(&policy);
    record_verify_proof_closure(&proof_closure);
    print_verify_policy_outcome(&policy);
    print_verify_proof_closure(&proof_closure);
    // Phase 2.6 temporal-authority closure: fail closed when any axis
    // (temporal authority, hash chain, or signed chain) voted Reject or
    // Quarantine in the composition. If the inner walk already returned a
    // non-Ok exit (chain corruption, integrity failure), preserve that more
    // specific exit so operators see the precise root cause.
    let exit = match policy.final_outcome {
        PolicyOutcome::Reject | PolicyOutcome::Quarantine if inner_exit == Exit::Ok => {
            Exit::IntegrityFailure
        }
        _ => inner_exit,
    };
    if output::json_enabled() {
        let mut report = VERIFY_REPORT.with(VerifyReport::take_or_default);
        // ADR 0037 §5 amendment: populate the typed truth-ceiling triad
        // on the verify report. `audit verify` does not promote claims,
        // so the runtime mode is `local_unsigned` when the chain is
        // clean (or signed-clean if a signed chain was verified); the
        // proof state follows the observed chain integrity and the
        // claim ceiling clamps to the weakest signal.
        let (runtime_mode, proof_state) = verify_report_runtime_mode_and_proof_state(&report, exit);
        let authority_class = AuthorityClass::Observed;
        let requested_ceiling = ClaimCeiling::LocalUnsigned;
        let claim_ceiling = cortex_core::effective_ceiling(
            runtime_mode,
            authority_class,
            proof_state,
            requested_ceiling,
        );
        report.runtime_mode = runtime_mode;
        report.proof_state = proof_state;
        report.claim_ceiling = claim_ceiling;
        report.authority_class = authority_class;
        let policy_summary = policy_outcome_summary(&policy);
        let envelope =
            Envelope::new("cortex.audit.verify", exit, report).with_policy_outcome(policy_summary);
        output::emit(&envelope, exit)
    } else {
        exit
    }
}

/// Compute the ADR 0037 truth-ceiling triad fields for a `VerifyReport`.
///
/// Fail-closed shape:
/// * Chain corruption / IntegrityFailure exit → `proof_state = Broken`.
/// * Clean chain with signed verification observed → `runtime_mode =
///   SignedLocalLedger`, `proof_state = FullChainVerified`.
/// * Clean chain without signed verification → `runtime_mode =
///   LocalUnsigned`, `proof_state = FullChainVerified`.
/// * Any other case (precondition unmet, internal failure) →
///   `proof_state = Unknown`.
fn verify_report_runtime_mode_and_proof_state(
    report: &VerifyReport,
    exit: Exit,
) -> (RuntimeMode, ClaimProofState) {
    match exit {
        Exit::Ok => {
            let runtime_mode = if report.signed_verification.is_some() {
                RuntimeMode::SignedLocalLedger
            } else {
                RuntimeMode::LocalUnsigned
            };
            (runtime_mode, ClaimProofState::FullChainVerified)
        }
        Exit::IntegrityFailure | Exit::ChainCorruption => {
            (RuntimeMode::LocalUnsigned, ClaimProofState::Broken)
        }
        _ => (RuntimeMode::LocalUnsigned, ClaimProofState::Unknown),
    }
}

fn run_verify_inner(args: VerifyArgs) -> Exit {
    // Load the operator self-signed key registry when the flag is supplied.
    // Fail early with `PreconditionUnmet` so a malformed path or TOML error
    // surfaces before any chain scanning begins.
    let _witness_key_registry: Option<SelfSignedKeyRegistry> =
        match args.witness_key_registry.as_deref() {
            None => None,
            Some(path) => match SelfSignedKeyRegistry::load(path) {
                Ok(registry) => {
                    eprintln!(
                        "audit verify: witness-key-registry loaded {} key(s) from `{}`",
                        registry.len(),
                        path.display()
                    );
                    Some(registry)
                }
                Err(e) => {
                    eprintln!("audit verify: {e}");
                    return Exit::PreconditionUnmet;
                }
            },
        };

    let layout = match DataLayout::resolve(args.db, args.event_log) {
        Ok(l) => l,
        Err(e) => return e,
    };
    // BUG-1: Reject a non-existent event-log path before opening it.
    // `JsonlLog::open` uses `create(true)` which would silently create an
    // empty file, causing verify_chain to scan 0 rows and report success.
    // Only the verify subcommand needs this guard; anchor/export legitimately
    // create the log when it does not yet exist.
    if !layout.event_log_path.exists() {
        eprintln!(
            "audit verify: event-log path does not exist: {}",
            layout.event_log_path.display()
        );
        return Exit::PreconditionUnmet;
    }
    if args.signed {
        let key_inputs =
            usize::from(args.verification_key.is_some()) + usize::from(args.attestation.is_some());
        if key_inputs == 0 {
            eprintln!(
                "audit verify: --signed requires --verification-key <KEY_PATH> or local-development --attestation <KEY_PATH>; no trusted verification was performed"
            );
            return Exit::PreconditionUnmet;
        }
        if key_inputs > 1 {
            eprintln!("audit verify: use only one of --verification-key or --attestation");
            return Exit::Usage;
        }
        let (verifying_key, key_id) =
            if let Some(verification_key_path) = args.verification_key.as_ref() {
                match load_verifying_key_from_file(verification_key_path) {
                    Ok(key) => key,
                    Err(exit) => return exit,
                }
            } else {
                let attestation_path = args
                    .attestation
                    .as_ref()
                    .expect("attestation is present when verification key is absent");
                let attestor = match load_attestor_from_key_file(attestation_path) {
                    Ok(attestor) => attestor,
                    Err(exit) => return exit,
                };
                (attestor.verifying_key(), attestor.key_id().to_string())
            };
        match verify_signed_chain(&layout.event_log_path, &verifying_key, &key_id) {
            Ok(outcome) => {
                print_report(&outcome.report);
                if output::json_enabled() {
                    VERIFY_REPORT.with(|cell| {
                        let mut r = cell.borrow_mut();
                        let entry = r.get_or_insert_with(VerifyReport::default);
                        entry.signed_verification = Some(SignedVerification {
                            key_id: key_id.clone(),
                        });
                    });
                }
                if outcome.report.ok() {
                    record_verify_contribution(
                        VERIFY_HASH_CHAIN_CLOSURE_RULE_ID,
                        PolicyOutcome::Allow,
                        "hash chain verified end to end with no per-row failures",
                    );
                    record_verify_contribution(
                        VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID,
                        PolicyOutcome::Allow,
                        "signed chain verified against the supplied verification key",
                    );
                    // Phase 2.6 closure: `verify_signed_chain` is purely
                    // Ed25519, so the temporal axis must be revalidated
                    // against the durable timeline rather than implied by
                    // Ed25519 success. `minimum_trust_tier = Verified` per
                    // audit §6.2 (signed-chain audit inherits the chain's
                    // minimum tier). A revoked / retired / sub-`Verified`
                    // key votes `Quarantine` or `Reject` here and the
                    // composed final outcome reflects that.
                    record_temporal_authority_contribution_for_audit_verify(&key_id);
                    verify_post_chain_requirements(
                        &layout.event_log_path,
                        args.require_v1_to_v2_boundary,
                        args.against.as_ref(),
                        args.against_history.as_ref(),
                        args.against_external.as_ref(),
                    )
                } else {
                    // Per-row failures fail closed on the hash-chain
                    // contributor: a single bad row collapses the chain
                    // closure for ADR 0021 / 0022 even though the file is
                    // structurally parseable.
                    record_verify_contribution(
                        VERIFY_HASH_CHAIN_CLOSURE_RULE_ID,
                        PolicyOutcome::Reject,
                        "hash chain verification produced per-row failures",
                    );
                    record_verify_contribution(
                        VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID,
                        PolicyOutcome::Reject,
                        "signed chain verification produced per-row failures",
                    );
                    // Phase 2.6 closure: emit the temporal contributor
                    // even on a failing chain so its absence cannot be
                    // read as silent `Allow` for the temporal axis.
                    record_temporal_authority_contribution_for_audit_verify(&key_id);
                    Exit::IntegrityFailure
                }
            }
            Err(e) => {
                eprintln!(
                    "audit verify: signed chain corruption ({}): {e}",
                    layout.event_log_path.display(),
                );
                record_verify_contribution(
                    VERIFY_HASH_CHAIN_CLOSURE_RULE_ID,
                    PolicyOutcome::Reject,
                    "hash chain could not be scanned (JSONL corruption)",
                );
                record_verify_contribution(
                    VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID,
                    PolicyOutcome::Reject,
                    "signed chain could not be verified (JSONL corruption)",
                );
                record_temporal_authority_contribution_for_audit_verify(&key_id);
                map_open_err(&e)
            }
        }
    } else if args.attestation.is_some() || args.verification_key.is_some() {
        eprintln!(
            "audit verify: --attestation and --verification-key are only valid with --signed"
        );
        Exit::Usage
    } else {
        match verify_chain(&layout.event_log_path) {
            Ok(report) => {
                print_report(&report);
                if report.ok() {
                    record_verify_contribution(
                        VERIFY_HASH_CHAIN_CLOSURE_RULE_ID,
                        PolicyOutcome::Allow,
                        "hash chain verified end to end with no per-row failures",
                    );
                    verify_post_chain_requirements(
                        &layout.event_log_path,
                        args.require_v1_to_v2_boundary,
                        args.against.as_ref(),
                        args.against_history.as_ref(),
                        args.against_external.as_ref(),
                    )
                } else {
                    record_verify_contribution(
                        VERIFY_HASH_CHAIN_CLOSURE_RULE_ID,
                        PolicyOutcome::Reject,
                        "hash chain verification produced per-row failures",
                    );
                    Exit::IntegrityFailure
                }
            }
            Err(e) => {
                eprintln!(
                    "audit verify: chain corruption ({}): {e}",
                    layout.event_log_path.display(),
                );
                record_verify_contribution(
                    VERIFY_HASH_CHAIN_CLOSURE_RULE_ID,
                    PolicyOutcome::Reject,
                    "hash chain could not be scanned (JSONL corruption)",
                );
                map_open_err(&e)
            }
        }
    }
}

fn verify_post_chain_requirements(
    path: &PathBuf,
    require_v1_to_v2_boundary: bool,
    against: Option<&PathBuf>,
    against_history: Option<&PathBuf>,
    against_external: Option<&PathBuf>,
) -> Exit {
    let boundary_exit = verify_required_v1_to_v2_boundary(path, require_v1_to_v2_boundary);
    if boundary_exit != Exit::Ok {
        return boundary_exit;
    }
    let anchor_exit = verify_against_anchor(path, against);
    if anchor_exit != Exit::Ok {
        return anchor_exit;
    }
    let history_exit = verify_against_anchor_history(path, against_history);
    if history_exit != Exit::Ok {
        return history_exit;
    }
    verify_against_external_receipts(path, against_external)
}

fn verify_required_v1_to_v2_boundary(path: &PathBuf, required: bool) -> Exit {
    if !required {
        record_boundary(BoundaryReport {
            required: false,
            ok: true,
            failures: Vec::new(),
        });
        // When the caller did not require the boundary, this contributor
        // does not block default verification: it simply observes that
        // the boundary check was not requested.
        record_verify_contribution(
            VERIFY_V1_TO_V2_BOUNDARY_RULE_ID,
            PolicyOutcome::Allow,
            "schema v1 to v2 boundary check was not requested",
        );
        return Exit::Ok;
    }

    match verify_schema_migration_v1_to_v2_boundary(path, true) {
        Ok(report) if report.ok() => {
            record_boundary(BoundaryReport {
                required: true,
                ok: true,
                failures: Vec::new(),
            });
            record_verify_contribution(
                VERIFY_V1_TO_V2_BOUNDARY_RULE_ID,
                PolicyOutcome::Allow,
                "schema v1 to v2 boundary verified",
            );
            Exit::Ok
        }
        Ok(report) => {
            let mut failures = Vec::new();
            for failure in &report.failures {
                let line = format!("{}: {:?}", failure.invariant, failure.detail);
                eprintln!("audit verify: {line}");
                failures.push(line);
            }
            record_boundary(BoundaryReport {
                required: true,
                ok: false,
                failures,
            });
            record_verify_contribution(
                VERIFY_V1_TO_V2_BOUNDARY_RULE_ID,
                PolicyOutcome::Reject,
                "schema v1 to v2 boundary failed required invariants",
            );
            eprintln!(
                "audit verify: hint: if this is a fresh v2 store, the boundary check may be a \
                 false positive — run `cortex doctor --repair` to confirm; for a migrated store \
                 run `cortex migrate v2 --backup-manifest <path>` to complete the upgrade"
            );
            Exit::SchemaMismatch
        }
        Err(e) => {
            eprintln!(
                "audit verify: failed to verify schema boundary events ({}): {e}",
                path.display()
            );
            record_boundary(BoundaryReport {
                required: true,
                ok: false,
                failures: vec![format!("failed to verify schema boundary events: {e}")],
            });
            record_verify_contribution(
                VERIFY_V1_TO_V2_BOUNDARY_RULE_ID,
                PolicyOutcome::Reject,
                "schema v1 to v2 boundary could not be scanned",
            );
            map_open_err(&e)
        }
    }
}

fn record_boundary(boundary: BoundaryReport) {
    if !output::json_enabled() {
        return;
    }
    VERIFY_REPORT.with(|cell| {
        let mut report_ref = cell.borrow_mut();
        let entry = report_ref.get_or_insert_with(VerifyReport::default);
        entry.boundary = Some(boundary);
    });
}

fn verify_against_anchor(path: &PathBuf, against: Option<&PathBuf>) -> Exit {
    let Some(anchor_path) = against else {
        return Exit::Ok;
    };
    let text = match std::fs::read_to_string(anchor_path) {
        Ok(text) => text,
        Err(err) => {
            eprintln!(
                "audit verify: cannot read --against anchor file `{}`: {err}",
                anchor_path.display()
            );
            return Exit::PreconditionUnmet;
        }
    };
    let anchor = match parse_anchor(&text) {
        Ok(anchor) => anchor,
        Err(err) => {
            eprintln!(
                "audit verify: invalid --against anchor file `{}`: {err}",
                anchor_path.display()
            );
            return Exit::PreconditionUnmet;
        }
    };
    match verify_anchor(path, &anchor) {
        Ok(verified) => {
            if !output::json_enabled() {
                println!(
                    "audit verify: anchor {} matched event_count {} ({} rows scanned)",
                    anchor_path.display(),
                    verified.anchor.event_count,
                    verified.db_count
                );
            }
            VERIFY_REPORT.with(|cell| {
                let mut r = cell.borrow_mut();
                let entry = r.get_or_insert_with(VerifyReport::default);
                entry.anchor = Some(AnchorMatch {
                    anchor_path: anchor_path.display().to_string(),
                    event_count: verified.anchor.event_count,
                    db_count: verified.db_count,
                });
            });
            Exit::Ok
        }
        Err(AnchorVerifyError::Jsonl(err)) => {
            eprintln!(
                "audit verify: anchor verification could not scan ledger ({}): {err}",
                path.display()
            );
            map_open_err(&err)
        }
        Err(err) => {
            eprintln!(
                "audit verify: anchor verification failed for `{}` against `{}`: {err}",
                anchor_path.display(),
                path.display()
            );
            Exit::IntegrityFailure
        }
    }
}

fn verify_against_anchor_history(path: &PathBuf, against_history: Option<&PathBuf>) -> Exit {
    let Some(history_path) = against_history else {
        return Exit::Ok;
    };
    match verify_anchor_history(path, history_path) {
        Ok(verified) => {
            if !output::json_enabled() {
                println!(
                    "audit verify: anchor history {} verified {} anchors through event_count {} ({} rows scanned)",
                    history_path.display(),
                    verified.anchors_verified,
                    verified.latest_anchor.event_count,
                    verified.db_count
                );
            }
            VERIFY_REPORT.with(|cell| {
                let mut r = cell.borrow_mut();
                let entry = r.get_or_insert_with(VerifyReport::default);
                entry.anchor_history = Some(AnchorHistoryMatch {
                    history_path: history_path.display().to_string(),
                    anchors_verified: verified.anchors_verified,
                    latest_event_count: verified.latest_anchor.event_count,
                    db_count: verified.db_count,
                });
            });
            Exit::Ok
        }
        Err(AnchorHistoryVerifyError::ReadHistory { source, .. }) => {
            eprintln!(
                "audit verify: cannot read --against-history anchor history `{}`: {source}",
                history_path.display()
            );
            Exit::PreconditionUnmet
        }
        Err(AnchorHistoryVerifyError::Parse { source, .. }) => {
            eprintln!(
                "audit verify: invalid --against-history anchor history `{}`: {source}",
                history_path.display()
            );
            Exit::PreconditionUnmet
        }
        Err(AnchorHistoryVerifyError::Anchor { source, .. })
            if matches!(source.as_ref(), AnchorVerifyError::Jsonl(_)) =>
        {
            let AnchorVerifyError::Jsonl(err) = *source else {
                unreachable!("guard ensures boxed anchor source is a JSONL error")
            };
            eprintln!(
                "audit verify: anchor history verification could not scan ledger ({}): {err}",
                path.display()
            );
            map_open_err(&err)
        }
        Err(err @ AnchorHistoryVerifyError::NonMonotonic { .. })
        | Err(err @ AnchorHistoryVerifyError::Anchor { .. }) => {
            eprintln!(
                "audit verify: anchor history verification failed for `{}` against `{}`: {err}",
                history_path.display(),
                path.display()
            );
            Exit::IntegrityFailure
        }
    }
}

fn verify_against_external_receipts(path: &PathBuf, against_external: Option<&PathBuf>) -> Exit {
    let Some(receipts_path) = against_external else {
        return Exit::Ok;
    };
    let trust_root_cache = trust_root_cache_path();
    let now = Utc::now();
    let result = cortex_ledger::external_sink::verify_external_receipts_with_options(
        path,
        receipts_path.clone(),
        trust_root_cache.as_deref(),
        now,
        cortex_ledger::external_sink::DEFAULT_MAX_TRUST_ROOT_AGE,
    );
    match result {
        Ok(verified) => {
            if !output::json_enabled() {
                println!(
                    "audit verify: external anchor receipts {} parsed and verified {} receipts through event_count {} ({} rows scanned)",
                    receipts_path.display(),
                    verified.receipts_verified,
                    verified.latest_receipt.anchor_event_count,
                    verified.db_count
                );
            }

            // ADR 0013 Gate 4: OpenTimestamps receipts go through the
            // trait wrapper for an extra trust-path layer beyond the
            // parser-only anchor_text_sha256 check. Pending always maps
            // to Partial; tampered Bitcoin attestations are Broken.
            let ots_exit = verify_ots_receipts_in_history(receipts_path);
            if ots_exit != Exit::Ok {
                return ots_exit;
            }

            // Slice 3 of Gate 4: when any receipt declares `sink=rekor`,
            // run the live offline verifier (ECDSA P-256 over SET +
            // SHA-256 Merkle inclusion). Authorized by
            // docs/decisions/COUNCIL_TIEBREAKS_2026_05_14.md Decision #2.
            // When the latest receipt is not Rekor, `live_status` falls
            // through to the parsed-only token so the OpenTimestamps and
            // legacy paths keep their existing surface.
            let live_status =
                match run_live_rekor_verification(receipts_path, &verified.latest_receipt) {
                    Ok(status) => status,
                    Err(exit) => return exit,
                };
            eprintln!("audit verify: external_anchor_authority={live_status}");
            eprintln!(
                "audit verify: external_anchor_receipts_verified={}",
                verified.receipts_verified
            );
            eprintln!("audit verify: external_anchor_status={live_status}");
            eprintln!(
                "audit verify: trust_root_status={}",
                verified.trust_root_status
            );
            if let Some(signed_at) = verified.trust_root_signed_at {
                eprintln!("audit verify: trust_root_signed_at={signed_at}");
            }
            // Embedded fallback is warn-only: operators should refresh
            // before relying on the external-anchor authority surface
            // for anything more than parser confidence.
            //
            // 2026-05-15 portfolio extension of the Bug J footnote: when
            // the embedded snapshot itself is older than the operator
            // policy, surface the stable `...snapshot_stale` invariant
            // (warn, do not fail) so dashboards can correlate. Anchor
            // is the build-time snapshot capture date, NOT the Sigstore
            // tlog activation inside the JSON.
            if verified.trust_root_status == cortex_ledger::external_sink::EMBEDDED_ROOT_STATUS {
                eprintln!(
                    "audit verify: warning: embedded trusted_root.json snapshot is in force; run `cortex audit refresh-trust` to install a fresh cache"
                );
                let embedded_stale = TrustedRoot::embedded()
                    .ok()
                    .and_then(|root| {
                        root.is_stale(Utc::now(), TrustRootStalenessAnchor::embedded_snapshot())
                            .ok()
                    })
                    .unwrap_or(false);
                if embedded_stale {
                    eprintln!(
                        "audit verify: invariant={}",
                        cortex_ledger::TRUSTED_ROOT_SNAPSHOT_STALE_INVARIANT
                    );
                    eprintln!(
                        "audit verify: invariant={}",
                        cortex_ledger::TRUSTED_ROOT_STALE_INVARIANT
                    );
                }
            }
            VERIFY_REPORT.with(|cell| {
                let mut r = cell.borrow_mut();
                let entry = r.get_or_insert_with(VerifyReport::default);
                entry.external_receipts = Some(ExternalReceiptsMatch {
                    receipts_path: receipts_path.display().to_string(),
                    receipts_verified: verified.receipts_verified,
                    latest_anchor_event_count: verified.latest_receipt.anchor_event_count,
                    db_count: verified.db_count,
                    external_anchor_authority: live_status,
                    status: live_status.to_string(),
                    trust_root_status: verified.trust_root_status,
                    trust_root_signed_at: verified.trust_root_signed_at.map(|ts| ts.to_rfc3339()),
                });
            });
            Exit::Ok
        }
        Err(ExternalReceiptVerifyError::ReadHistory { source, .. }) => {
            eprintln!(
                "audit verify: cannot read --against-external receipts `{}`: {source}",
                receipts_path.display()
            );
            Exit::PreconditionUnmet
        }
        Err(ExternalReceiptVerifyError::Parse { source, .. }) => {
            eprintln!(
                "audit verify: invalid --against-external receipts `{}`: {source}",
                receipts_path.display()
            );
            // Non-monotonic histories are an `IntegrityFailure` per design;
            // structural parse failures (unknown format header, missing
            // body, malformed field shapes) are operator preconditions.
            match source {
                cortex_ledger::ExternalReceiptParseError::NonMonotonic { .. } => {
                    Exit::IntegrityFailure
                }
                _ => Exit::PreconditionUnmet,
            }
        }
        Err(ExternalReceiptVerifyError::Anchor { source, .. }) => {
            eprintln!(
                "audit verify: external anchor receipts `{}` carry malformed anchor metadata: {source}",
                receipts_path.display()
            );
            Exit::PreconditionUnmet
        }
        Err(ExternalReceiptVerifyError::AnchorVerify { source, .. })
            if matches!(source.as_ref(), AnchorVerifyError::Jsonl(_)) =>
        {
            let AnchorVerifyError::Jsonl(err) = *source else {
                unreachable!("guard ensures boxed anchor source is a JSONL error")
            };
            eprintln!(
                "audit verify: external receipt verification could not scan ledger ({}): {err}",
                path.display()
            );
            map_open_err(&err)
        }
        Err(err @ ExternalReceiptVerifyError::AnchorVerify { .. })
        | Err(err @ ExternalReceiptVerifyError::AnchorTextHashMismatch { .. }) => {
            if let ExternalReceiptVerifyError::AnchorTextHashMismatch { invariant, .. } = &err {
                eprintln!("audit verify: invariant={invariant}");
                debug_assert_eq!(*invariant, ANCHOR_TEXT_HASH_MISMATCH_INVARIANT);
            }
            eprintln!(
                "audit verify: external receipt verification failed for `{}` against `{}`: {err}",
                receipts_path.display(),
                path.display()
            );
            Exit::IntegrityFailure
        }
        Err(ExternalReceiptVerifyError::TrustedRootStale {
            invariant,
            trust_root_status,
            cache_path,
            signed_at,
            now,
            max_age,
        }) => {
            // Council Decision #1 (+ 2026-05-15 portfolio-extension
            // footnote on Bug J): a cached trusted root whose file
            // mtime has aged past the operator policy must refuse to
            // mark anchor authority authoritative. The embedded-
            // fallback branch is already filtered out by the verifier
            // (warn-only); reaching this arm means the operator ran
            // refresh-trust at least once and has not refreshed within
            // `max_age`. Both the specific (`...cache_stale`) and
            // legacy generic (`...stale_beyond_max_age`) tokens are
            // surfaced so existing dashboards keep working.
            eprintln!("audit verify: invariant={invariant}");
            eprintln!(
                "audit verify: invariant={}",
                cortex_ledger::TRUSTED_ROOT_STALE_INVARIANT
            );
            eprintln!(
                "audit verify: external_anchor_authority=fail_closed_trusted_root_stale_>30d"
            );
            eprintln!("audit verify: trust_root_status={trust_root_status}");
            if let Some(signed_at) = signed_at {
                eprintln!("audit verify: trust_root_signed_at={signed_at}");
            }
            if let Some(cache_path) = cache_path.as_ref() {
                eprintln!(
                    "audit verify: trust_root_cache_path={}",
                    cache_path.display()
                );
            }
            eprintln!(
                "audit verify: cached trusted_root.json is stale at {now} (max_age={max_age:?}); run `cortex audit refresh-trust`"
            );
            VERIFY_REPORT.with(|cell| {
                let mut r = cell.borrow_mut();
                let entry = r.get_or_insert_with(VerifyReport::default);
                entry.external_receipts = Some(ExternalReceiptsMatch {
                    receipts_path: receipts_path.display().to_string(),
                    receipts_verified: 0,
                    latest_anchor_event_count: 0,
                    db_count: 0,
                    external_anchor_authority: "fail_closed_trusted_root_stale_>30d",
                    status: invariant.to_string(),
                    trust_root_status,
                    trust_root_signed_at: signed_at.map(|ts| ts.to_rfc3339()),
                });
            });
            Exit::PreconditionUnmet
        }
        Err(ExternalReceiptVerifyError::TrustedRootIo {
            invariant,
            path: trust_root_path,
            source,
        }) => {
            eprintln!("audit verify: invariant={invariant}");
            eprintln!(
                "audit verify: failed to load trusted_root.json at `{}`: {source}",
                trust_root_path.display()
            );
            Exit::PreconditionUnmet
        }
    }
}

/// Run the OpenTimestamps trait-wrapper trust path over every receipt
/// in an external anchor receipt history file. Receipts whose `sink`
/// is not `opentimestamps` are passed through unchanged.
///
/// Pending receipts always map to Partial — the
/// `ots.pending.no_bitcoin_attestation_yet` token is surfaced verbatim
/// on stderr so the drill script can grep for it. Tampered Bitcoin
/// attestations fail closed with the stable
/// `ots.bitcoin_confirmed.merkle_path_invalid` token.
///
/// 2026-05-15 finding-2 closure: after the per-receipt verification,
/// the council-mandated N>=2 disjoint-authority quorum gate
/// ([`enforce_disjoint_authority_quorum`]) is applied to every
/// `FullChainVerified` candidate against the union of witnesses across
/// the entire receipt history. A history with only Peter-Todd-operated
/// calendar endpoints (any combination of `a.pool`, `alice`, `bob`)
/// never produces a `FullChainVerified` result — it is downgraded to
/// `Partial` with the stable
/// `ots.disjoint_authority.quorum_not_met` invariant. At least one
/// non-Todd witness (e.g. Eternitywall's `finney.calendar`) is
/// required.
fn verify_ots_receipts_in_history(receipts_path: &PathBuf) -> Exit {
    let receipts = match cortex_ledger::read_external_receipt_history(receipts_path) {
        Ok(receipts) => receipts,
        Err(err) => {
            eprintln!(
                "audit verify: cannot reread --against-external receipts `{}` for OTS pass: {err}",
                receipts_path.display()
            );
            return Exit::PreconditionUnmet;
        }
    };
    let mut pending_count = 0usize;
    let mut bitcoin_partial_count = 0usize;
    let mut bitcoin_verified_count = 0usize;
    let mut quorum_partial_count = 0usize;

    // Council 2026-05-12 Q2 + Q3 (UNANIMOUS): when `CORTEX_OTS_LIVE=1`
    // and no operator-supplied static `--bitcoin-header` is wired, the
    // verify path MUST construct `HttpsHeadersBitcoinHeaderSource`
    // (N>=2 disjoint HTTPS providers + local PoW). Default offline CI
    // stays on `None`, mirroring the pre-2026-05-12 posture.
    let live_https_source: Option<cortex_ledger::HttpsHeadersBitcoinHeaderSource> =
        if ots_live_mode_enabled() {
            Some(cortex_ledger::HttpsHeadersBitcoinHeaderSource::new(
                live_bitcoin_header_providers(),
            ))
        } else {
            None
        };
    let bitcoin_dyn: Option<&dyn cortex_ledger::BitcoinHeaderSource> = live_https_source
        .as_ref()
        .map(|s| s as &dyn cortex_ledger::BitcoinHeaderSource);

    // First pass: per-receipt verification + witness collection. We
    // need every OTS receipt's witness summary in scope BEFORE running
    // the quorum gate, because the quorum gate decides promotion based
    // on the union of witnesses across the whole history (not just the
    // current receipt). This mirrors the doctrine on
    // `enforce_disjoint_authority_quorum`.
    struct PerReceipt {
        record_index: usize,
        outcome: cortex_ledger::OtsVerificationOutcome,
    }
    let mut per_receipt: Vec<PerReceipt> = Vec::new();
    let mut history_witnesses: Vec<OtsWitness> = Vec::new();
    for (index, receipt) in receipts.iter().enumerate() {
        if receipt.sink != cortex_ledger::ExternalSink::OpenTimestamps {
            continue;
        }
        // Parser-only path: a receipt body without `ots_proof_base64` is
        // a synthetic envelope (e.g. operator imported a sidecar from a
        // non-live calendar workflow). The anchor_text_sha256 check
        // already verified position binding against the local ledger; we
        // do NOT run the OTS proof verifier when there is no proof to
        // verify.
        if receipt.receipt.get("ots_proof_base64").is_none() {
            continue;
        }
        let record_index = index + 1;
        let outcome = match cortex_ledger::verify_ots_receipt_with_defaults(receipt, bitcoin_dyn) {
            Ok(outcome) => outcome,
            Err(err) => {
                eprintln!(
                    "audit verify: OTS receipt {} in `{}` parser rejected the proof: {err}",
                    record_index,
                    receipts_path.display()
                );
                // UnknownTag is an IntegrityFailure (the tag whitelist
                // is a trust-path edge); MalformedHeader / EmptyProof
                // are operator preconditions.
                let exit = match err {
                    cortex_ledger::OtsError::UnknownTag { .. } => Exit::IntegrityFailure,
                    _ => Exit::PreconditionUnmet,
                };
                return exit;
            }
        };
        // Snapshot the witnesses contributed by this receipt into the
        // history-wide pool the quorum gate will consume.
        match &outcome {
            cortex_ledger::OtsVerificationOutcome::FullChainVerified { witnesses } => {
                history_witnesses.extend(witnesses.iter().cloned());
            }
            cortex_ledger::OtsVerificationOutcome::Partial { witnesses, .. } => {
                history_witnesses.extend(witnesses.iter().cloned());
            }
            cortex_ledger::OtsVerificationOutcome::Broken { witnesses, .. } => {
                history_witnesses.extend(witnesses.iter().cloned());
            }
        }
        per_receipt.push(PerReceipt {
            record_index,
            outcome,
        });
    }

    // Second pass: apply the quorum gate to every per-receipt outcome
    // against the union of witnesses across the entire history.
    for entry in per_receipt {
        let PerReceipt {
            record_index,
            outcome,
        } = entry;
        let gated = enforce_disjoint_authority_quorum(outcome, &history_witnesses);
        match gated {
            cortex_ledger::OtsVerificationOutcome::FullChainVerified { .. } => {
                bitcoin_verified_count += 1;
            }
            cortex_ledger::OtsVerificationOutcome::Partial { reasons, .. } => {
                let is_pending = reasons
                    .iter()
                    .any(|r| r == cortex_ledger::OTS_PENDING_NO_BITCOIN_ATTESTATION_YET_INVARIANT);
                let is_quorum_not_met = reasons
                    .iter()
                    .any(|r| r == OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT);
                if is_pending {
                    pending_count += 1;
                    eprintln!(
                        "audit verify: invariant={}",
                        cortex_ledger::OTS_PENDING_NO_BITCOIN_ATTESTATION_YET_INVARIANT
                    );
                } else if is_quorum_not_met {
                    quorum_partial_count += 1;
                    eprintln!(
                        "audit verify: invariant={OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT}"
                    );
                    eprintln!(
                        "audit verify: OTS receipt {} in `{}` held at Partial: quorum of N>=2 disjoint operators not met across receipt history. add a witness from a non-Todd calendar (e.g. eternitywall.com) to reach FullChainVerified.",
                        record_index,
                        receipts_path.display()
                    );
                } else {
                    bitcoin_partial_count += 1;
                    eprintln!(
                        "audit verify: invariant={}",
                        cortex_ledger::OTS_BITCOIN_CONFIRMED_BLOCK_HEADER_MISMATCH_INVARIANT
                    );
                }
            }
            cortex_ledger::OtsVerificationOutcome::Broken { edge, .. } => {
                eprintln!("audit verify: invariant={}", edge.invariant);
                eprintln!(
                    "audit verify: OTS receipt {} in `{}` failed closed: {}",
                    record_index,
                    receipts_path.display(),
                    edge.detail
                );
                return Exit::IntegrityFailure;
            }
        }
    }
    if pending_count > 0
        || bitcoin_partial_count > 0
        || bitcoin_verified_count > 0
        || quorum_partial_count > 0
    {
        eprintln!(
            "audit verify: ots_receipts_pending={pending_count} \
             ots_receipts_bitcoin_partial={bitcoin_partial_count} \
             ots_receipts_bitcoin_full_chain_verified={bitcoin_verified_count} \
             ots_receipts_quorum_not_met={quorum_partial_count}"
        );
    }
    Exit::Ok
}

/// When the latest external anchor receipt declares `sink=rekor`, run
/// the live offline verifier (ECDSA P-256 over SET + SHA-256 Merkle
/// inclusion) against the embedded trust root. Returns the canonical
/// `external_anchor_authority` token to surface in the report.
fn run_live_rekor_verification(
    receipts_path: &std::path::Path,
    latest: &ExternalReceipt,
) -> Result<&'static str, Exit> {
    if latest.sink != ExternalSink::Rekor {
        return Ok(PARSED_ONLY_VERIFICATION_STATUS);
    }
    // Parser-only path: a Rekor-sinked receipt without the live-verify
    // body fields (`body`, `inclusionProof`, `signedEntryTimestamp`) is
    // a synthetic envelope an operator imported out-of-band. The
    // `anchor_text_sha256` check has already validated position binding
    // against the local ledger; we do NOT run the Rekor verifier when
    // there is no SET signature or inclusion proof to verify. Strong
    // (live) verification requires the full body shape and is the path
    // the anchor drill exercises against a real Rekor instance.
    let live_fields_present = latest.receipt.get("body").is_some()
        && latest.receipt.get("inclusionProof").is_some()
        && latest.receipt.get("signedEntryTimestamp").is_some();
    if !live_fields_present {
        return Ok(PARSED_ONLY_VERIFICATION_STATUS);
    }
    let trusted_root = match TrustedRoot::from_embedded() {
        Ok(root) => root,
        Err(err) => {
            eprintln!(
                "audit verify: failed to load embedded trusted root for live Rekor verification of `{}`: {err}",
                receipts_path.display()
            );
            return Err(Exit::Internal);
        }
    };
    match rekor_verify_receipt(latest, &trusted_root) {
        Ok(verification) => {
            eprintln!(
                "audit verify: rekor entry uuid={} log_index={}",
                verification.uuid, verification.log_index
            );
            Ok(REKOR_EXTERNAL_AUTHORITY_STATUS)
        }
        Err(err) => {
            let (invariant, reason) = rekor_error_invariant(&err);
            // `audit.verify.rekor.signature_mismatch` is the stable
            // verify-side invariant for a tampered SET signature; the
            // adapter-side error invariants are the same as the anchor
            // path so the prose line stays uniform across both
            // commands.
            if matches!(err, RekorError::SetSignatureInvalid { .. }) {
                eprintln!("audit verify: invariant={REKOR_VERIFY_SIGNATURE_MISMATCH_INVARIANT}");
            }
            eprintln!("audit verify: invariant={invariant}");
            eprintln!(
                "audit verify: rekor live verification failed for receipts `{}`: {reason}",
                receipts_path.display()
            );
            Err(Exit::IntegrityFailure)
        }
    }
}

/// Run `cortex audit anchor`.
///
/// This is ADR 0013 local anchor publication. It proves a current position-bound
/// tuple can be derived from the verified JSONL ledger, but it is still local
/// evidence unless the operator publishes the text to a disjoint append-only
/// sink.
pub fn run_anchor(args: AnchorArgs) -> Exit {
    ANCHOR_POLICY_OUTCOME.with(|cell| cell.borrow_mut().take());
    let exit = run_anchor_inner(args);
    if output::json_enabled() {
        let report = ANCHOR_REPORT.with(|cell| cell.borrow_mut().take().unwrap_or_default());
        let envelope = match ANCHOR_POLICY_OUTCOME.with(|cell| cell.borrow().clone()) {
            Some(policy) => Envelope::new("cortex.audit.anchor", exit, report)
                .with_policy_outcome(policy_outcome_summary(&policy)),
            None => Envelope::new("cortex.audit.anchor", exit, report),
        };
        output::emit(&envelope, exit)
    } else {
        exit
    }
}

thread_local! {
    static ANCHOR_REPORT: std::cell::RefCell<Option<AnchorReport>> =
        const { std::cell::RefCell::new(None) };
    static ANCHOR_POLICY_OUTCOME: std::cell::RefCell<Option<PolicyDecision>> =
        const { std::cell::RefCell::new(None) };
}

#[derive(Debug, Serialize)]
struct AnchorReport {
    sink: Option<String>,
    anchor_authority: Option<String>,
    external_anchor_sink_configured: bool,
    external_anchor_authority: bool,
    /// Stable status string when the Rekor live adapter succeeds. Mirrors
    /// the `--sink rekor` happy-path prose line so JSON consumers can
    /// grep for `external_authority_rekor` without parsing prose.
    #[serde(skip_serializing_if = "Option::is_none")]
    external_anchor_authority_status: Option<&'static str>,
    anchor_sink_reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    anchor_text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    event_count: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    chain_head_hash: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    output_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    history_path: Option<String>,
    /// Truth-ceiling field: the JSON envelope must NOT laundering a local
    /// anchor as authoritative. Mirrors the `anchor_authority` prose line.
    #[serde(skip_serializing_if = "Option::is_none")]
    forbidden_uses: Option<Vec<&'static str>>,
    /// ADR 0037 §5 amendment: typed truth-ceiling triad. `runtime_mode`
    /// promotes to `externally_anchored` only after a live external sink
    /// (Rekor / OpenTimestamps) verifies and the trusted root is fresh;
    /// otherwise it stays at `local_unsigned`. `proof_state` follows the
    /// composed anchor sink decision; `claim_ceiling` clamps to the
    /// weakest signal. The stringy `forbidden_uses` shape stays for
    /// backward compatibility — both shapes drive the same fail-closed
    /// enforcement at downstream consumers.
    runtime_mode: RuntimeMode,
    proof_state: ClaimProofState,
    claim_ceiling: ClaimCeiling,
    authority_class: AuthorityClass,
    /// Composed ADR 0026 policy outcome over the
    /// `audit.anchor.sink_authority` contributor. Mirrors the top-level
    /// envelope `policy_outcome` field for consumers that inspect the
    /// report directly.
    #[serde(skip_serializing_if = "Option::is_none")]
    policy_outcome: Option<AnchorPolicyOutcome>,
    /// Rekor entry index returned by the live adapter (slice 2 of Gate 4).
    #[serde(skip_serializing_if = "Option::is_none")]
    rekor_log_index: Option<u64>,
    /// Rekor entry UUID returned by the live adapter.
    #[serde(skip_serializing_if = "Option::is_none")]
    rekor_uuid: Option<String>,
    /// Base64-encoded Rekor SignedEntryTimestamp signature.
    #[serde(skip_serializing_if = "Option::is_none")]
    rekor_set_signature: Option<String>,
    /// RFC 3339 timestamp from the embedded Sigstore TUF trust root.
    #[serde(skip_serializing_if = "Option::is_none")]
    trusted_root_signed_at: Option<String>,
    /// Path of the on-disk Rekor receipt sidecar written by `--sink-receipt`.
    #[serde(skip_serializing_if = "Option::is_none")]
    rekor_receipt_path: Option<String>,
    /// Path of the on-disk Rekor receipt history journal written by
    /// `--sink-receipt-history`.
    #[serde(skip_serializing_if = "Option::is_none")]
    rekor_receipt_history_path: Option<String>,
}

impl Default for AnchorReport {
    fn default() -> Self {
        // Fail-closed defaults: until a sink decision is observed, treat
        // the anchor as `local_unsigned` with unknown proof state. This
        // matches the §5 amendment's "fail-closed value if the producer
        // didn't set it" requirement.
        Self {
            sink: None,
            anchor_authority: None,
            external_anchor_sink_configured: false,
            external_anchor_authority: false,
            external_anchor_authority_status: None,
            anchor_sink_reason: None,
            anchor_text: None,
            event_count: None,
            chain_head_hash: None,
            output_path: None,
            history_path: None,
            forbidden_uses: None,
            runtime_mode: RuntimeMode::LocalUnsigned,
            proof_state: ClaimProofState::Unknown,
            claim_ceiling: ClaimCeiling::DevOnly,
            authority_class: AuthorityClass::Observed,
            policy_outcome: None,
            rekor_log_index: None,
            rekor_uuid: None,
            rekor_set_signature: None,
            trusted_root_signed_at: None,
            rekor_receipt_path: None,
            rekor_receipt_history_path: None,
        }
    }
}

#[derive(Debug, Serialize)]
struct AnchorPolicyOutcome {
    final_outcome: PolicyOutcome,
    contributing: Vec<PolicyContribution>,
    discarded: Vec<PolicyContribution>,
}

impl AnchorPolicyOutcome {
    fn from_decision(policy: &PolicyDecision) -> Self {
        Self {
            final_outcome: policy.final_outcome,
            contributing: policy.contributing.clone(),
            discarded: policy.discarded.clone(),
        }
    }
}

fn run_anchor_inner(args: AnchorArgs) -> Exit {
    let sink_decision = anchor_sink_decision(args.sink, args.sink_path.as_ref());
    if output::json_enabled() {
        ANCHOR_REPORT.with(|cell| {
            let mut r = cell.borrow_mut();
            let entry = r.get_or_insert_with(AnchorReport::default);
            entry.sink = Some(args.sink.wire_str().to_string());
        });
    }
    if args.sink == AnchorSink::LocalOnly && args.sink_path.is_some() {
        print_anchor_authority_report(&sink_decision, None);
        eprintln!(
            "audit anchor: --sink-path is only valid with --sink external-append-only; no anchor was emitted or written"
        );
        return Exit::Usage;
    }
    if args.sink == AnchorSink::LocalOnly
        && (args.sink_endpoint.is_some()
            || args.sink_receipt.is_some()
            || args.sink_receipt_history.is_some()
            || args.offline)
    {
        print_anchor_authority_report(&sink_decision, None);
        eprintln!(
            "audit anchor: --sink-endpoint/--sink-receipt/--sink-receipt-history/--offline are only valid with an --sink external-* selector; no anchor was emitted or written"
        );
        return Exit::Usage;
    }
    if args.sink == AnchorSink::ExternalAppendOnly {
        print_anchor_authority_report(&sink_decision, None);
        eprintln!(
            "audit anchor: --sink external-append-only requires a configured disjoint append-only sink; no anchor was emitted or written"
        );
        return Exit::PreconditionUnmet;
    }
    // Both Rekor (Decision #2) and OpenTimestamps (Decisions #3/#4) now
    // have live adapters; the per-sink decision logic below is
    // responsible for the actual authority determination.
    if args.sink == AnchorSink::Rekor {
        return run_anchor_rekor(&args);
    }

    if args.sink == AnchorSink::OpenTimestamps {
        return run_anchor_opentimestamps(args);
    }

    let layout = match DataLayout::resolve(args.db, args.event_log) {
        Ok(l) => l,
        Err(e) => return e,
    };
    let anchor = match current_anchor(&layout.event_log_path, Utc::now()) {
        Ok(anchor) => anchor,
        Err(AnchorVerifyError::Jsonl(err)) => {
            eprintln!(
                "audit anchor: cannot scan ledger ({}): {err}",
                layout.event_log_path.display()
            );
            return map_open_err(&err);
        }
        Err(err) => {
            eprintln!(
                "audit anchor: cannot publish anchor for `{}`: {err}",
                layout.event_log_path.display()
            );
            return Exit::IntegrityFailure;
        }
    };

    let text = anchor.to_anchor_text();
    if let Some(history) = args.history.as_ref() {
        let exit = validate_anchor_history_before_append(&layout.event_log_path, history);
        if exit != Exit::Ok {
            return exit;
        }
    }

    if let Some(output) = args.output.as_ref() {
        let mut file = match OpenOptions::new().write(true).create_new(true).open(output) {
            Ok(file) => file,
            Err(err) => {
                eprintln!(
                    "audit anchor: failed to create anchor output `{}` without replacement: {err}",
                    output.display()
                );
                return Exit::PreconditionUnmet;
            }
        };
        if let Err(err) = write_and_sync(&mut file, text.as_bytes()) {
            eprintln!(
                "audit anchor: failed to write anchor output `{}`: {err}",
                output.display()
            );
            return Exit::Internal;
        }
    }

    if let Some(history) = args.history.as_ref() {
        let mut file = match OpenOptions::new().append(true).create(true).open(history) {
            Ok(file) => file,
            Err(err) => {
                eprintln!(
                    "audit anchor: failed to open anchor history `{}` for append: {err}",
                    history.display()
                );
                return Exit::PreconditionUnmet;
            }
        };
        if let Err(err) = write_and_sync(&mut file, text.as_bytes()) {
            eprintln!(
                "audit anchor: failed to append anchor history `{}`: {err}",
                history.display()
            );
            return Exit::Internal;
        }
    }

    if !output::json_enabled() {
        print!("{text}");
    }
    print_anchor_authority_report(&sink_decision, Some(&layout.event_log_path));
    if let Some(history) = args.history.as_ref() {
        eprintln!(
            "audit anchor: appended local anchor history `{}` through event_count {}",
            history.display(),
            anchor.event_count
        );
    } else if let Some(output) = args.output.as_ref() {
        eprintln!(
            "audit anchor: wrote local anchor `{}` at event_count {}",
            output.display(),
            anchor.event_count
        );
    } else {
        eprintln!(
            "audit anchor: emitted local anchor at event_count {}; publish to a disjoint append-only sink for stronger authority",
            anchor.event_count
        );
    }
    if output::json_enabled() {
        ANCHOR_REPORT.with(|cell| {
            let mut r = cell.borrow_mut();
            let entry = r.get_or_insert_with(AnchorReport::default);
            entry.anchor_text = Some(text);
            entry.event_count = Some(anchor.event_count);
            entry.chain_head_hash = Some(anchor.chain_head_hash.clone());
            entry.output_path = args.output.as_ref().map(|p| p.display().to_string());
            entry.history_path = args.history.as_ref().map(|p| p.display().to_string());
        });
    }
    Exit::Ok
}

/// Environment gate that flips the OTS CLI from the offline / pre-fetched
/// posture (`NoopCalendarClient` + static `--bitcoin-header` only) to the
/// council-ratified live posture: live `UreqCalendarClient` submission
/// across the 4-URL [`DEFAULT_OTS_CALENDAR_URLS`] set (council Q1) and
/// the N>=2 HTTPS [`HttpsHeadersBitcoinHeaderSource`] for the Bitcoin
/// header cross-check (council Q2 + Q3).
///
/// Mirrors the `CORTEX_REKOR_LIVE=1` convention used by the Rekor live
/// path. Default CI MUST stay offline; this gate is opt-in.
pub const CORTEX_OTS_LIVE_ENV: &str = "CORTEX_OTS_LIVE";

/// Optional CSV override of the [`DEFAULT_HTTPS_HEADER_PROVIDERS`] list
/// consumed by [`HttpsHeadersBitcoinHeaderSource`] when
/// `CORTEX_OTS_LIVE=1`. Brief §7 of
/// `docs/council-briefings/BRIEF_2026-05-12_OTS_btc_header_transport.md`
/// lists this as a supported operator override; the quorum gate still
/// requires `N>=2` byte-identical responses regardless of provider
/// count.
pub const CORTEX_OTS_BTC_HEADER_PROVIDERS_ENV: &str = "CORTEX_OTS_BTC_HEADER_PROVIDERS";

/// Returns `true` when the operator opted into live OTS submission +
/// verify via `CORTEX_OTS_LIVE=1`. Any other value (including unset)
/// keeps the offline posture.
fn ots_live_mode_enabled() -> bool {
    std::env::var(CORTEX_OTS_LIVE_ENV)
        .map(|v| v.trim() == "1")
        .unwrap_or(false)
}

/// Resolve the HTTPS Bitcoin header provider list for live mode.
/// Returns the operator-supplied CSV override
/// (`CORTEX_OTS_BTC_HEADER_PROVIDERS`) when set and non-empty, otherwise
/// falls back to [`cortex_ledger::DEFAULT_HTTPS_HEADER_PROVIDERS`].
fn live_bitcoin_header_providers() -> Vec<String> {
    if let Ok(raw) = std::env::var(CORTEX_OTS_BTC_HEADER_PROVIDERS_ENV) {
        let providers: Vec<String> = raw
            .split(',')
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .collect();
        if !providers.is_empty() {
            return providers;
        }
    }
    cortex_ledger::DEFAULT_HTTPS_HEADER_PROVIDERS
        .iter()
        .map(|s| (*s).to_string())
        .collect()
}

/// Run the live OpenTimestamps anchor path (operator decisions #3 + #4,
/// ADR 0013 Gate 4).
///
/// Submits the canonical anchor text SHA-256 to a calendar (currently
/// only via the `--sink-receipt-in` pre-fetched file path, because
/// cortex-ledger does not yet ship a built-in HTTP client per the
/// Slice 1 Cargo.lock rule), then verifies the resulting receipt
/// through the [`cortex_ledger::OtsParser`] trait wrapper and applies
/// the `--require-non-pending` / `--allow-pending` policy lattice.
fn run_anchor_opentimestamps(args: AnchorArgs) -> Exit {
    use cortex_ledger::{
        submit_ots, verify_ots_receipt_with_defaults, BitcoinHeaderSource,
        HttpsHeadersBitcoinHeaderSource, NoopCalendarClient, OtsError, UreqCalendarClient,
        DEFAULT_OTS_CALENDAR_URL, DEFAULT_OTS_CALENDAR_URLS,
    };

    if args.allow_pending && args.require_non_pending {
        // clap's `conflicts_with` should already block this, but a
        // defensive guard makes the wire contract explicit.
        eprintln!(
            "audit anchor: --allow-pending and --require-non-pending are mutually exclusive; \
             pick at most one"
        );
        return Exit::Usage;
    }
    let allow_pending = args.allow_pending;

    let layout = match DataLayout::resolve(args.db, args.event_log) {
        Ok(l) => l,
        Err(e) => return e,
    };
    let anchor = match current_anchor(&layout.event_log_path, Utc::now()) {
        Ok(anchor) => anchor,
        Err(AnchorVerifyError::Jsonl(err)) => {
            eprintln!(
                "audit anchor: cannot scan ledger ({}): {err}",
                layout.event_log_path.display()
            );
            return map_open_err(&err);
        }
        Err(err) => {
            eprintln!(
                "audit anchor: cannot publish anchor for `{}`: {err}",
                layout.event_log_path.display()
            );
            return Exit::IntegrityFailure;
        }
    };

    // Council 2026-05-12 Q1 (UNANIMOUS) + Q5 (UNANIMOUS) + Decision #4
    // of `COUNCIL_TIEBREAKS_2026_05_14.md`:
    //
    // - If `--sink-endpoint` is set: operator-pinned single URL.
    //   (Operators may use this for an air-gapped internal proxy or
    //   to add a 5th disjoint witness; the per-invocation override is
    //   preserved.)
    // - Else if `CORTEX_OTS_LIVE=1`: fan out across
    //   `DEFAULT_OTS_CALENDAR_URLS` (the four-entry council Q1 set)
    //   so the disjoint-authority quorum gate can actually function.
    //   The single-URL back-compat alias `DEFAULT_OTS_CALENDAR_URL`
    //   cannot reach `OTS_DISJOINT_AUTHORITY_MIN_OPERATORS = 2` by
    //   construction (one Todd-operator host) so live mode MUST NOT
    //   resolve to it.
    // - Else: the single-URL back-compat alias remains for the
    //   offline / pre-fetched-bytes documentation path.
    let live_mode = ots_live_mode_enabled();
    let calendar_urls: Vec<String> = if let Some(endpoint) = args.sink_endpoint.as_deref() {
        vec![endpoint.to_string()]
    } else if live_mode {
        DEFAULT_OTS_CALENDAR_URLS
            .iter()
            .map(|s| (*s).to_string())
            .collect()
    } else {
        vec![DEFAULT_OTS_CALENDAR_URL.to_string()]
    };
    let submitted_at = Utc::now();

    // Acquire the .ots bytes — either via `--sink-receipt-in` (operator
    // pre-fetched out-of-band) or via the calendar client. The default
    // posture pre-2026-05-12 was `NoopCalendarClient`; the council Q5
    // UNANIMOUS ratification authorizes `UreqCalendarClient` as the
    // live default when `CORTEX_OTS_LIVE=1` is set.
    //
    // When `--sink-receipt-in` is supplied, all `calendar_urls` resolve
    // to the same pre-fetched proof bytes; this preserves the drill
    // script's per-invocation determinism.
    let mut receipts: Vec<cortex_ledger::ExternalReceipt> = Vec::with_capacity(calendar_urls.len());
    match args.sink_receipt_in.as_ref() {
        Some(path) => {
            for url in &calendar_urls {
                match build_receipt_from_pre_fetched_bytes(&anchor, url, submitted_at, path) {
                    Ok(receipt) => receipts.push(receipt),
                    Err(exit) => return exit,
                }
            }
        }
        None => {
            let live_client = UreqCalendarClient::new();
            let noop_client = NoopCalendarClient;
            for url in &calendar_urls {
                let submission = if live_mode {
                    submit_ots(&anchor, url, submitted_at, &live_client)
                } else {
                    submit_ots(&anchor, url, submitted_at, &noop_client)
                };
                match submission {
                    Ok(receipt) => receipts.push(receipt),
                    Err(OtsError::OtsCrateError(reason))
                        if reason.contains("NoopCalendarClient") =>
                    {
                        eprintln!(
                            "audit anchor: --sink opentimestamps requires either \
                             --sink-receipt-in, `CORTEX_OTS_LIVE=1` (live UreqCalendarClient), \
                             or an operator-supplied CalendarClient build; default \
                             NoopCalendarClient refused the submission ({reason})"
                        );
                        let decision = AnchorSinkDecision {
                            authority_label: "external_unconfigured",
                            external_configured: false,
                            external_authority: false,
                            reason: EXTERNAL_SINK_ADAPTER_NOT_YET_IMPLEMENTED_REASON,
                            policy_outcome: PolicyOutcome::Reject,
                        };
                        print_anchor_authority_report(&decision, Some(&layout.event_log_path));
                        return Exit::PreconditionUnmet;
                    }
                    Err(err) => {
                        eprintln!("audit anchor: OTS submit to {url} failed: {err}");
                        return Exit::PreconditionUnmet;
                    }
                }
            }
        }
    }

    // Verify each receipt through the trait wrapper. Pending always
    // maps to Partial; BitcoinConfirmed promotes to FullChainVerified
    // only when the Bitcoin header source confirms the cited height's
    // merkle root.
    //
    // Council 2026-05-12 Q2 + Q3 (UNANIMOUS): when `CORTEX_OTS_LIVE=1`
    // and no `--bitcoin-header` is supplied, the CLI MUST construct
    // `HttpsHeadersBitcoinHeaderSource` (N>=2 administratively-disjoint
    // HTTPS providers + local PoW). `--bitcoin-header` remains the
    // operator override for air-gapped / pre-baked workflows.
    enum AnchorBitcoinSource {
        Static(cortex_ledger::StaticBitcoinHeaderSource),
        Https(HttpsHeadersBitcoinHeaderSource),
    }
    let bitcoin_source: Option<AnchorBitcoinSource> = match args.bitcoin_header.as_ref() {
        Some(path) => match load_bitcoin_header(path) {
            Ok(source) => Some(AnchorBitcoinSource::Static(source)),
            Err(exit) => return exit,
        },
        None if live_mode => Some(AnchorBitcoinSource::Https(
            HttpsHeadersBitcoinHeaderSource::new(live_bitcoin_header_providers()),
        )),
        None => None,
    };
    let bitcoin_dyn: Option<&dyn BitcoinHeaderSource> = match bitcoin_source.as_ref() {
        Some(AnchorBitcoinSource::Static(s)) => Some(s as &dyn BitcoinHeaderSource),
        Some(AnchorBitcoinSource::Https(s)) => Some(s as &dyn BitcoinHeaderSource),
        None => None,
    };

    // Per-receipt verification with witness collection so the
    // disjoint-authority quorum gate can compose across the full
    // fan-out. The gate is a no-op for non-`FullChainVerified`
    // outcomes, but it is the *only* path that surfaces
    // `ots.disjoint_authority.quorum_not_met` at the CLI emit site
    // (closing Hole A from
    // `docs/design/INVARIANT_COVERAGE_audit_2026-05-12.md`).
    let mut per_receipt_outcomes: Vec<cortex_ledger::OtsVerificationOutcome> =
        Vec::with_capacity(receipts.len());
    let mut history_witnesses: Vec<OtsWitness> = Vec::new();
    for receipt in &receipts {
        let outcome = match verify_ots_receipt_with_defaults(receipt, bitcoin_dyn) {
            Ok(outcome) => outcome,
            Err(err) => {
                eprintln!("audit anchor: OTS receipt verification failed: {err}");
                let exit = match err {
                    OtsError::UnknownTag { .. } => Exit::IntegrityFailure,
                    OtsError::EmptyProof | OtsError::MalformedHeader { .. } => {
                        Exit::PreconditionUnmet
                    }
                    _ => Exit::PreconditionUnmet,
                };
                return exit;
            }
        };
        match &outcome {
            cortex_ledger::OtsVerificationOutcome::FullChainVerified { witnesses } => {
                history_witnesses.extend(witnesses.iter().cloned());
            }
            cortex_ledger::OtsVerificationOutcome::Partial { witnesses, .. } => {
                history_witnesses.extend(witnesses.iter().cloned());
            }
            cortex_ledger::OtsVerificationOutcome::Broken { witnesses, .. } => {
                history_witnesses.extend(witnesses.iter().cloned());
            }
        }
        per_receipt_outcomes.push(outcome);
    }

    // Apply the disjoint-authority quorum gate across the per-receipt
    // outcomes against the union of witnesses. The first
    // post-gate outcome carries the receipt selected for sidecar
    // emission below; the witness diagnostic surfaces on stderr.
    let mut quorum_not_met_count: usize = 0;
    let mut gated_outcomes: Vec<cortex_ledger::OtsVerificationOutcome> =
        Vec::with_capacity(per_receipt_outcomes.len());
    for raw_outcome in per_receipt_outcomes {
        let gated = enforce_disjoint_authority_quorum(raw_outcome, &history_witnesses);
        if let cortex_ledger::OtsVerificationOutcome::Partial { reasons, .. } = &gated {
            if reasons
                .iter()
                .any(|r| r == OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT)
            {
                quorum_not_met_count += 1;
            }
        }
        gated_outcomes.push(gated);
    }

    // Pick the best outcome for the operator-facing sidecar:
    // `FullChainVerified` > any `Partial` > any `Broken`. Doctrine
    // note: even one survivor of `FullChainVerified` after the gate is
    // enough to authorize the strong-mode anchor.
    let representative_index = pick_representative_anchor_outcome(&gated_outcomes);
    let outcome = gated_outcomes[representative_index].clone();
    let receipt = receipts[representative_index].clone();
    if quorum_not_met_count > 0 {
        eprintln!("audit anchor: invariant={OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT}");
        eprintln!(
            "audit anchor: OTS receipt quorum gate downgraded {quorum_not_met_count} of {} receipt(s) — disjoint-authority quorum of N>=2 distinct operators not met. Add a witness from a non-Todd calendar (e.g. finney.calendar.eternitywall.com) to reach FullChainVerified.",
            receipts.len()
        );
    }

    let decision = ots_anchor_sink_decision(&outcome, allow_pending);

    // Persist the receipt sidecar(s) if the operator asked for one and
    // the policy lattice did not Reject. Quarantine and Allow both
    // produce an artifact; Reject does not.
    //
    // `--sink-receipt` captures the **representative** receipt (the one
    // whose verification outcome drove the policy decision). The
    // append-only `--sink-receipt-history` captures **every** receipt
    // produced this invocation so a follow-up `cortex audit verify
    // --against-external` sees the full fan-out the disjoint-authority
    // quorum gate consumed.
    let representative_text = match receipt.to_record_text() {
        Ok(text) => text,
        Err(err) => {
            eprintln!("audit anchor: failed to serialize OTS receipt: {err}");
            return Exit::Internal;
        }
    };
    if matches!(
        decision.policy_outcome,
        PolicyOutcome::Allow | PolicyOutcome::Quarantine | PolicyOutcome::Warn
    ) {
        if let Some(output) = args.sink_receipt.as_ref() {
            let mut file = match OpenOptions::new().write(true).create_new(true).open(output) {
                Ok(file) => file,
                Err(err) => {
                    eprintln!(
                        "audit anchor: failed to create OTS receipt output `{}`: {err}",
                        output.display()
                    );
                    return Exit::PreconditionUnmet;
                }
            };
            if let Err(err) = write_and_sync(&mut file, representative_text.as_bytes()) {
                eprintln!(
                    "audit anchor: failed to write OTS receipt output `{}`: {err}",
                    output.display()
                );
                return Exit::Internal;
            }
        }
        if let Some(history) = args.sink_receipt_history.as_ref() {
            let mut file = match OpenOptions::new().append(true).create(true).open(history) {
                Ok(file) => file,
                Err(err) => {
                    eprintln!(
                        "audit anchor: failed to open OTS receipt history `{}`: {err}",
                        history.display()
                    );
                    return Exit::PreconditionUnmet;
                }
            };
            for r in &receipts {
                let text = match r.to_record_text() {
                    Ok(text) => text,
                    Err(err) => {
                        eprintln!("audit anchor: failed to serialize OTS receipt: {err}");
                        return Exit::Internal;
                    }
                };
                if let Err(err) = write_and_sync(&mut file, text.as_bytes()) {
                    eprintln!(
                        "audit anchor: failed to append OTS receipt history `{}`: {err}",
                        history.display()
                    );
                    return Exit::Internal;
                }
            }
        }
    }

    if !output::json_enabled() {
        // Mirror the canonical anchor text on stdout so the operator
        // can pipe it the same way as the local-only path.
        print!("{}", anchor.to_anchor_text());
    }
    print_anchor_authority_report(&decision, Some(&layout.event_log_path));
    eprintln!(
        "audit anchor: ots_outcome={} (sink_endpoint={})",
        outcome.wire_str(),
        receipt.sink_endpoint
    );
    if output::json_enabled() {
        ANCHOR_REPORT.with(|cell| {
            let mut r = cell.borrow_mut();
            let entry = r.get_or_insert_with(AnchorReport::default);
            entry.anchor_text = Some(anchor.to_anchor_text());
            entry.event_count = Some(anchor.event_count);
            entry.chain_head_hash = Some(anchor.chain_head_hash.clone());
            entry.output_path = args.sink_receipt.as_ref().map(|p| p.display().to_string());
            entry.history_path = args
                .sink_receipt_history
                .as_ref()
                .map(|p| p.display().to_string());
        });
    }
    // Map the final policy outcome onto the CLI exit table. Reject is
    // PreconditionUnmet (operator misconfiguration: chose
    // --require-non-pending but the calendar still has a Pending proof
    // for them), Allow / Quarantine / Warn return Ok.
    match decision.policy_outcome {
        PolicyOutcome::Reject => Exit::PreconditionUnmet,
        _ => Exit::Ok,
    }
}

// =============================================================================
// Live Rekor anchor + verify path (council Decision #2 / #4 — Gate 4 slice 2).
// =============================================================================

/// Live Rekor submit + verify path. Authorized by
/// `docs/decisions/COUNCIL_TIEBREAKS_2026_05_14.md` (commit `1eb93b6`)
/// Decision #2 (P-256 at adapter boundary) and Decision #4 (dep set).
fn run_anchor_rekor(args: &AnchorArgs) -> Exit {
    if args.offline {
        let outcome = RekorAdapterOutcome::Rejected {
            invariant: REKOR_SUBMIT_FAILED_INVARIANT,
            reason: "--offline forbids live Rekor submission".to_string(),
        };
        let decision = rekor_anchor_sink_decision(&outcome);
        print_anchor_authority_report(&decision, None);
        eprintln!(
            "audit anchor: --sink rekor refused with --offline; live submission requires network reachability"
        );
        return Exit::PreconditionUnmet;
    }

    let layout = match DataLayout::resolve(args.db.clone(), args.event_log.clone()) {
        Ok(layout) => layout,
        Err(exit) => return exit,
    };
    let anchor = match current_anchor(&layout.event_log_path, Utc::now()) {
        Ok(anchor) => anchor,
        Err(AnchorVerifyError::Jsonl(err)) => {
            eprintln!(
                "audit anchor: cannot scan ledger ({}): {err}",
                layout.event_log_path.display()
            );
            return map_open_err(&err);
        }
        Err(err) => {
            eprintln!(
                "audit anchor: cannot publish anchor for `{}`: {err}",
                layout.event_log_path.display()
            );
            return Exit::IntegrityFailure;
        }
    };

    let trusted_root = match TrustedRoot::from_embedded() {
        Ok(root) => root,
        Err(err) => {
            let outcome = RekorAdapterOutcome::Rejected {
                invariant: REKOR_VERIFY_FAILED_INVARIANT,
                reason: format!("failed to load embedded trusted root: {err}"),
            };
            let decision = rekor_anchor_sink_decision(&outcome);
            print_anchor_authority_report(&decision, Some(&layout.event_log_path));
            eprintln!("audit anchor: rekor adapter: {err}");
            return Exit::Internal;
        }
    };
    let trusted_root_signed_at = trusted_root.signed_at();
    // Anchor against the embedded snapshot capture date. The 2026-05-12
    // Bug J footnote (extended 2026-05-15 to all trust-root staleness
    // call sites) clarifies that the operator-meaningful freshness
    // datum is the snapshot-capture date, NOT the Sigstore tlog
    // signing-key activation inside the JSON. This call site only ever
    // loads the embedded root (`TrustedRoot::from_embedded()` above), so
    // the snapshot-date anchor is unambiguously the right choice.
    let trusted_root_stale = trusted_root
        .is_stale(Utc::now(), TrustRootStalenessAnchor::embedded_snapshot())
        .unwrap_or(true);

    let endpoint = args
        .sink_endpoint
        .as_deref()
        .unwrap_or(REKOR_DEFAULT_ENDPOINT);

    let receipt = match rekor_submit(&anchor, endpoint) {
        Ok(receipt) => receipt,
        Err(err) => {
            let (invariant, reason) = rekor_error_invariant(&err);
            let outcome = RekorAdapterOutcome::Rejected { invariant, reason };
            let decision = rekor_anchor_sink_decision(&outcome);
            print_anchor_authority_report(&decision, Some(&layout.event_log_path));
            eprintln!("audit anchor: rekor submission failed: {err}");
            return Exit::Internal;
        }
    };

    let verification = match rekor_verify_receipt(&receipt, &trusted_root) {
        Ok(v) => v,
        Err(err) => {
            let (invariant, reason) = rekor_error_invariant(&err);
            let outcome = RekorAdapterOutcome::Rejected { invariant, reason };
            let decision = rekor_anchor_sink_decision(&outcome);
            print_anchor_authority_report(&decision, Some(&layout.event_log_path));
            eprintln!("audit anchor: rekor verification failed: {err}");
            return Exit::IntegrityFailure;
        }
    };

    let outcome = if trusted_root_stale {
        RekorAdapterOutcome::QuarantineTrustedRootStale
    } else {
        RekorAdapterOutcome::Allowed
    };
    let decision = rekor_anchor_sink_decision(&outcome);

    // Persist receipt sidecar / history if the operator requested it.
    let receipt_text = match receipt.to_record_text() {
        Ok(text) => text,
        Err(err) => {
            eprintln!("audit anchor: failed to render rekor receipt: {err}");
            return Exit::Internal;
        }
    };
    if let Some(receipt_path) = args.sink_receipt.as_ref() {
        let mut file = match OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(receipt_path)
        {
            Ok(file) => file,
            Err(err) => {
                eprintln!(
                    "audit anchor: failed to create rekor receipt output `{}` without replacement: {err}",
                    receipt_path.display()
                );
                return Exit::PreconditionUnmet;
            }
        };
        if let Err(err) = write_and_sync(&mut file, receipt_text.as_bytes()) {
            eprintln!(
                "audit anchor: failed to write rekor receipt `{}`: {err}",
                receipt_path.display()
            );
            return Exit::Internal;
        }
    }
    if let Some(history_path) = args.sink_receipt_history.as_ref() {
        let mut file = match OpenOptions::new()
            .append(true)
            .create(true)
            .open(history_path)
        {
            Ok(file) => file,
            Err(err) => {
                eprintln!(
                    "audit anchor: failed to open rekor receipt history `{}` for append: {err}",
                    history_path.display()
                );
                return Exit::PreconditionUnmet;
            }
        };
        if let Err(err) = write_and_sync(&mut file, receipt_text.as_bytes()) {
            eprintln!(
                "audit anchor: failed to append rekor receipt history `{}`: {err}",
                history_path.display()
            );
            return Exit::Internal;
        }
    }

    print_anchor_authority_report(&decision, Some(&layout.event_log_path));
    eprintln!(
        "audit anchor: rekor entry uuid={} log_index={} endpoint={endpoint}",
        verification.uuid, verification.log_index,
    );
    eprintln!(
        "audit anchor: rekor trusted_root_signed_at={}",
        trusted_root_signed_at.to_rfc3339()
    );
    if trusted_root_stale {
        eprintln!(
            "audit anchor: rekor trusted root is older than 30 days; receipt is quarantined (invariant={REKOR_TRUSTED_ROOT_STALE_INVARIANT})"
        );
    }

    if output::json_enabled() {
        ANCHOR_REPORT.with(|cell| {
            let mut r = cell.borrow_mut();
            let entry = r.get_or_insert_with(AnchorReport::default);
            entry.anchor_text = Some(anchor.to_anchor_text());
            entry.event_count = Some(anchor.event_count);
            entry.chain_head_hash = Some(anchor.chain_head_hash.clone());
            entry.rekor_log_index = Some(verification.log_index);
            entry.rekor_uuid = Some(verification.uuid.clone());
            entry.rekor_set_signature = Some(verification.set_signature.clone());
            entry.trusted_root_signed_at = Some(trusted_root_signed_at.to_rfc3339());
            entry.rekor_receipt_path = args.sink_receipt.as_ref().map(|p| p.display().to_string());
            entry.rekor_receipt_history_path = args
                .sink_receipt_history
                .as_ref()
                .map(|p| p.display().to_string());
            if matches!(outcome, RekorAdapterOutcome::Allowed) {
                entry.external_anchor_authority_status = Some(REKOR_EXTERNAL_AUTHORITY_STATUS);
            }
        });
    }

    match outcome {
        RekorAdapterOutcome::Allowed => Exit::Ok,
        RekorAdapterOutcome::QuarantineTrustedRootStale => Exit::Ok,
        RekorAdapterOutcome::Rejected { .. } => unreachable!("rejected branches early-returned"),
    }
}

/// Map a [`RekorError`] into its stable invariant token plus a
/// human-readable reason for the policy report.
fn rekor_error_invariant(err: &RekorError) -> (&'static str, String) {
    match err {
        RekorError::SubmitHttp { invariant, reason }
        | RekorError::SubmitBody { invariant, reason } => (*invariant, reason.clone()),
        RekorError::WrongSink {
            invariant,
            observed,
        } => (*invariant, format!("wrong sink: {observed}")),
        RekorError::MalformedReceipt { invariant, reason } => (*invariant, reason.clone()),
        RekorError::SetSignatureInvalid { invariant, reason } => (*invariant, reason.clone()),
        RekorError::InclusionProofInvalid { invariant, reason } => (*invariant, reason.clone()),
        RekorError::TrustedRootStale {
            invariant,
            signed_at_rfc3339,
        } => (
            *invariant,
            format!("trusted root stale (signed_at={signed_at_rfc3339})"),
        ),
        // BH-3 (`docs/reviews/BUG_HUNT_2026-05-12_post_8f43450.md`
        // Finding 3, Cosign GHSA-whqx-f9j3-ch6m class): the receipt's
        // `body.logID` did not bind to any declared tlog
        // `logId.keyId` in the active trusted root. Carry the
        // `rekor.trusted_root.tlog_logid_no_match` invariant straight
        // through to the operator surface.
        RekorError::TlogLogIdUnknown {
            invariant,
            receipt_log_id,
            tlog_log_ids,
        } => (
            *invariant,
            format!(
                "rekor receipt logID `{receipt_log_id}` did not bind to any tlog in trusted_root (declared: {})",
                tlog_log_ids.join(", ")
            ),
        ),
    }
}

fn build_receipt_from_pre_fetched_bytes(
    anchor: &cortex_ledger::LedgerAnchor,
    calendar_url: &str,
    submitted_at: chrono::DateTime<chrono::Utc>,
    path: &PathBuf,
) -> Result<cortex_ledger::ExternalReceipt, Exit> {
    let bytes = std::fs::read(path).map_err(|err| {
        eprintln!(
            "audit anchor: cannot read --sink-receipt-in `{}`: {err}",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    let ots_bytes = bytes.clone();
    // Round-trip through the parser before we commit to a receipt
    // record, so a malformed input fails closed with a stable error.
    use cortex_ledger::OtsParser as _;
    match cortex_ledger::DefaultOtsParser.parse(&ots_bytes) {
        Ok(_) => {}
        Err(err) => {
            eprintln!(
                "audit anchor: --sink-receipt-in `{}` did not parse as a valid OTS proof: {err}",
                path.display()
            );
            return Err(Exit::PreconditionUnmet);
        }
    }
    Ok(cortex_ledger::ExternalReceipt {
        sink: cortex_ledger::ExternalSink::OpenTimestamps,
        anchor_text_sha256: cortex_ledger::anchor_text_sha256(anchor),
        anchor_event_count: anchor.event_count,
        anchor_chain_head_hash: anchor.chain_head_hash.clone(),
        submitted_at,
        sink_endpoint: calendar_url.to_string(),
        receipt: serde_json::json!({
            "ots_proof_base64": ots_proof_base64(&ots_bytes),
            "calendar_url": calendar_url,
            "submitted_digest_hex": cortex_ledger::anchor_text_sha256(anchor),
        }),
    })
}

/// Pick the index of the "best" outcome from a fan-out across the
/// council Q1 4-URL `DEFAULT_OTS_CALENDAR_URLS` set. Ranking:
///
/// 1. `FullChainVerified` — any one passes the quorum-gated promotion.
/// 2. `Partial` — degraded but not corrupted (pending /
///    quorum_not_met / block_header_mismatch).
/// 3. `Broken` — proof corruption surfaced by the parser.
///
/// Falls back to index 0 when the input is non-empty but all entries
/// share a rank class. Empty input is a programming error — caller
/// guarantees at least one receipt was produced.
fn pick_representative_anchor_outcome(outcomes: &[cortex_ledger::OtsVerificationOutcome]) -> usize {
    debug_assert!(
        !outcomes.is_empty(),
        "audit anchor: outcomes vector must be non-empty"
    );
    if let Some((idx, _)) = outcomes.iter().enumerate().find(|(_, o)| {
        matches!(
            o,
            cortex_ledger::OtsVerificationOutcome::FullChainVerified { .. }
        )
    }) {
        return idx;
    }
    if let Some((idx, _)) = outcomes
        .iter()
        .enumerate()
        .find(|(_, o)| matches!(o, cortex_ledger::OtsVerificationOutcome::Partial { .. }))
    {
        return idx;
    }
    0
}

fn load_bitcoin_header(path: &PathBuf) -> Result<cortex_ledger::StaticBitcoinHeaderSource, Exit> {
    let bytes = std::fs::read(path).map_err(|err| {
        eprintln!(
            "audit anchor: cannot read --bitcoin-header `{}`: {err}",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    if bytes.len() != 80 {
        eprintln!(
            "audit anchor: --bitcoin-header `{}` must be exactly 80 raw bytes; got {}",
            path.display(),
            bytes.len()
        );
        return Err(Exit::PreconditionUnmet);
    }
    // We cannot know the height from the header bytes alone (a real
    // operator workflow embeds the height in the filename or a sidecar
    // file). For the v1 surface we read a `<path>.height` neighbor
    // containing a decimal block height; this matches how the drill
    // script ships fixtures.
    let height_path = path.with_extension("height");
    let height_text = std::fs::read_to_string(&height_path).map_err(|err| {
        eprintln!(
            "audit anchor: --bitcoin-header `{}` requires a neighbor `{}` carrying the decimal block height: {err}",
            path.display(),
            height_path.display()
        );
        Exit::PreconditionUnmet
    })?;
    let height: u64 = height_text.trim().parse().map_err(|err| {
        eprintln!(
            "audit anchor: --bitcoin-header height file `{}` is not a decimal u64: {err}",
            height_path.display()
        );
        Exit::PreconditionUnmet
    })?;
    Ok(cortex_ledger::StaticBitcoinHeaderSource::new().with_header(height, bytes))
}

fn ots_proof_base64(bytes: &[u8]) -> String {
    // Module-private base64 encoder mirroring the cortex-ledger adapter
    // helper so the CLI does not pick up a `base64` crate dependency.
    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    let mut i = 0;
    while i + 3 <= bytes.len() {
        let triple = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | bytes[i + 2] as u32;
        out.push(TABLE[((triple >> 18) & 0x3f) as usize] as char);
        out.push(TABLE[((triple >> 12) & 0x3f) as usize] as char);
        out.push(TABLE[((triple >> 6) & 0x3f) as usize] as char);
        out.push(TABLE[(triple & 0x3f) as usize] as char);
        i += 3;
    }
    let remaining = bytes.len() - i;
    match remaining {
        1 => {
            let single = (bytes[i] as u32) << 16;
            out.push(TABLE[((single >> 18) & 0x3f) as usize] as char);
            out.push(TABLE[((single >> 12) & 0x3f) as usize] as char);
            out.push('=');
            out.push('=');
        }
        2 => {
            let pair = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);
            out.push(TABLE[((pair >> 18) & 0x3f) as usize] as char);
            out.push(TABLE[((pair >> 12) & 0x3f) as usize] as char);
            out.push(TABLE[((pair >> 6) & 0x3f) as usize] as char);
            out.push('=');
        }
        _ => {}
    }
    out
}

fn print_anchor_authority_report(decision: &AnchorSinkDecision, event_log_path: Option<&PathBuf>) {
    eprintln!(
        "audit anchor: anchor_authority={}",
        decision.authority_label
    );
    eprintln!(
        "audit anchor: external_anchor_sink_configured={}",
        decision.external_configured
    );
    eprintln!(
        "audit anchor: external_anchor_authority={}",
        decision.external_authority
    );
    eprintln!("audit anchor: anchor_sink_reason={}", decision.reason);
    // Phase 2.6 T3 closure: weakest-link compose the temporal authority
    // contributor across the signing keys observed in the anchored row
    // set. When the surface bailed before resolving a data layout (CLI
    // usage error path), emit `Reject` with the stable invariant rather
    // than silently dropping the contributor.
    let temporal_authority = match event_log_path {
        Some(path) => build_temporal_authority_contribution_for_row_set(
            path,
            "audit.anchor",
            ANCHOR_TEMPORAL_AUTHORITY_RULE_ID,
        ),
        None => {
            let invariant = revalidation_failed_invariant("audit.anchor");
            PolicyContribution::new(
                ANCHOR_TEMPORAL_AUTHORITY_RULE_ID,
                PolicyOutcome::Reject,
                format!(
                    "{invariant}: anchor surface bailed before resolving event log; temporal authority axis cannot be observed",
                ),
            )
            .expect("anchor temporal authority placeholder contribution is statically valid")
        }
    };
    let policy = compose_anchor_policy_decision(decision, temporal_authority);
    let final_outcome = policy.final_outcome;
    eprintln!("audit anchor: policy_outcome={final_outcome:?}");
    for contribution in &policy.contributing {
        let outcome = contribution.outcome;
        let rule_id = contribution.rule_id.as_str();
        let reason = contribution.reason.as_str();
        eprintln!(
            "audit anchor: policy_contributing={rule_id} outcome={outcome:?} reason={reason}"
        );
    }
    ANCHOR_POLICY_OUTCOME.with(|cell| *cell.borrow_mut() = Some(policy.clone()));
    if output::json_enabled() {
        ANCHOR_REPORT.with(|cell| {
            let mut r = cell.borrow_mut();
            let entry = r.get_or_insert_with(AnchorReport::default);
            entry.anchor_authority = Some(decision.authority_label.to_string());
            entry.external_anchor_sink_configured = decision.external_configured;
            entry.external_anchor_authority = decision.external_authority;
            entry.anchor_sink_reason = Some(decision.reason.to_string());
            // Truth-ceiling: a local-only or external-unconfigured anchor
            // cannot be used as compliance evidence or cross-system trust.
            if !decision.external_authority {
                entry.forbidden_uses = Some(vec![
                    "compliance_evidence",
                    "cross_system_trust_decision",
                    "external_reporting",
                ]);
            }
            entry.policy_outcome = Some(AnchorPolicyOutcome::from_decision(&policy));
            // ADR 0037 §5 amendment: typed truth-ceiling triad. The
            // stringy `forbidden_uses` set above stays as the
            // backward-compatible carrier; this typed shape lets an
            // operator inspecting the envelope grep the named mode/
            // ceiling without re-running the command.
            let (runtime_mode, proof_state) = if decision.external_authority {
                (
                    RuntimeMode::ExternallyAnchored,
                    ClaimProofState::FullChainVerified,
                )
            } else {
                (RuntimeMode::LocalUnsigned, ClaimProofState::Unknown)
            };
            let authority_class = if decision.external_authority {
                AuthorityClass::Verified
            } else {
                AuthorityClass::Observed
            };
            let requested_ceiling = if decision.external_authority {
                ClaimCeiling::ExternallyAnchored
            } else {
                ClaimCeiling::LocalUnsigned
            };
            let claim_ceiling = cortex_core::effective_ceiling(
                runtime_mode,
                authority_class,
                proof_state,
                requested_ceiling,
            );
            entry.runtime_mode = runtime_mode;
            entry.proof_state = proof_state;
            entry.claim_ceiling = claim_ceiling;
            entry.authority_class = authority_class;
        });
    }
}

fn compose_anchor_policy_decision(
    decision: &AnchorSinkDecision,
    temporal_authority: PolicyContribution,
) -> PolicyDecision {
    // ADR 0026 composer: the anchor surface contributes the existing
    // `audit.anchor.sink_authority` outcome plus the Phase 2.6 T3
    // `audit.anchor.temporal_authority` contributor derived from the
    // signing keys observed in the anchored row set. The composer routes
    // through `compose_policy_outcomes` so future contributors (sink
    // attestation, monotonicity check, etc.) can be added without
    // changing the call site.
    let reason = format!(
        "anchor sink `{}` resolved with reason `{}`",
        decision.authority_label, decision.reason,
    );
    let sink_contribution = PolicyContribution::new(
        ANCHOR_SINK_AUTHORITY_RULE_ID,
        decision.policy_outcome,
        reason,
    )
    .expect("anchor sink contribution is statically valid");
    compose_policy_outcomes(vec![sink_contribution, temporal_authority], None)
}

fn validate_anchor_history_before_append(ledger_path: &PathBuf, history: &PathBuf) -> Exit {
    if !history.exists() {
        return Exit::Ok;
    }
    match std::fs::metadata(history) {
        Ok(metadata) if metadata.len() > 0 => {
            let exit = verify_against_anchor_history(ledger_path, Some(history));
            if exit != Exit::Ok {
                eprintln!(
                    "audit anchor: existing anchor history `{}` did not verify; new anchor was not appended",
                    history.display()
                );
                return exit;
            }
            Exit::Ok
        }
        Ok(_) => Exit::Ok,
        Err(err) => {
            eprintln!(
                "audit anchor: cannot inspect anchor history `{}`: {err}",
                history.display()
            );
            Exit::PreconditionUnmet
        }
    }
}

fn write_and_sync(file: &mut std::fs::File, bytes: &[u8]) -> std::io::Result<()> {
    file.write_all(bytes)?;
    file.sync_all()
}

/// Run `cortex audit export`.
///
/// Phase 2 JSONL + SQLite run rows are development-ledger evidence. They may
/// support local diagnostics, but must not become audit export, compliance
/// evidence, cross-system trust decisions, or external reporting.
pub fn run_export(args: ExportArgs) -> Exit {
    let layout = match DataLayout::resolve(args.db, args.event_log) {
        Ok(l) => l,
        Err(e) => {
            return export_failure_envelope(e, "failed to resolve data layout", None);
        }
    };
    let report = match verify_chain(&layout.event_log_path) {
        Ok(report) if report.ok() => report,
        Ok(report) => {
            print_report(&report);
            return export_failure_envelope(
                Exit::IntegrityFailure,
                "chain verification reported failures",
                None,
            );
        }
        Err(e) => {
            eprintln!(
                "audit export: chain corruption ({}): {e}",
                layout.event_log_path.display(),
            );
            return export_failure_envelope(map_open_err(&e), "chain corruption", None);
        }
    };
    let scan = match scan_development_ledger_rows(
        &layout.event_log_path,
        args.surface.development_ledger_use(),
    ) {
        Ok(scan) => scan,
        Err(e) => {
            eprintln!(
                "audit export: failed to scan ledger authority ({}): {e}",
                layout.event_log_path.display(),
            );
            return export_failure_envelope(
                map_open_err(&e),
                "failed to scan ledger authority",
                None,
            );
        }
    };

    // ADR 0026 §2 composition: each contributor encodes a single concern
    // (development-ledger forbidden-use, signed-local authority class,
    // proof closure, and Phase 2.6 T3 temporal authority). They compose
    // uniformly across every `--surface` value so the default
    // `audit-export` surface no longer skips policy evaluation the way
    // the prior implementation did.
    let temporal_authority = build_temporal_authority_contribution_for_row_set(
        &layout.event_log_path,
        "audit.export",
        EXPORT_TEMPORAL_AUTHORITY_RULE_ID,
    );
    let policy = compose_export_policy_decision(
        &scan,
        args.surface,
        args.local_diagnostic,
        temporal_authority,
    );

    let authority_claim = runtime_claim_preflight_with_policy(
        format!("{} artifact", args.surface.label()),
        args.surface.runtime_claim_kind(),
        RuntimeMode::LocalUnsigned,
        AuthorityClass::Observed,
        ClaimProofState::Partial,
        args.surface.requested_ceiling(),
        &policy,
    );

    if scan.blocked_event_ids.is_empty() || args.local_diagnostic {
        // The default `audit-export` surface keeps the historical
        // contract of always reporting through the diagnostic artifact
        // even when policy fails, but every non-default surface (and an
        // explicit non-diagnostic invocation) now fails closed at the
        // shared runtime+policy preflight.
        if !args.local_diagnostic
            && !args.surface.is_default_audit_export()
            && !authority_claim.allowed
        {
            eprintln!(
                "audit export: {} preflight failed: {}; no trusted artifact emitted",
                args.surface.label(),
                authority_claim.reason
            );
            return export_failure_envelope(
                Exit::PreconditionUnmet,
                &format!(
                    "{} preflight failed: {}",
                    args.surface.label(),
                    authority_claim.reason
                ),
                Some(&policy),
            );
        }
        let artifact_kind = if !scan.blocked_event_ids.is_empty() {
            "development_ledger_diagnostic"
        } else if args.local_diagnostic {
            "local_diagnostic"
        } else {
            args.surface.artifact_kind()
        };
        let claim = runtime_claim_preflight(
            "local audit export artifact",
            RuntimeClaimKind::Advisory,
            RuntimeMode::LocalUnsigned,
            AuthorityClass::Observed,
            ClaimProofState::Partial,
            ClaimCeiling::LocalUnsigned,
        );
        let artifact = serde_json::json!({
            "artifact_schema": "cortex.audit_export.v1",
            "artifact_kind": artifact_kind,
            "runtime_mode": claim.claim.runtime_mode,
            "proof_state": claim.claim.proof_state,
            "claim_ceiling": claim.claim.effective_ceiling,
            "claim_allowed": claim.allowed,
            "downgrade_reasons": claim.claim.reasons,
            "requested_surface": args.surface.development_ledger_use().wire_str(),
            "authority_preflight_allowed": authority_claim.allowed,
            "authority_preflight_reason": authority_claim.reason,
            "policy_outcome": policy.final_outcome,
            "policy_contributing": policy.contributing,
            "policy_discarded": policy.discarded,
            "path": report.path,
            "rows_scanned": report.rows_scanned,
            "trusted_run_history": false,
            "development_ledger_rows": scan.blocked_event_ids.len(),
            "development_event_ids": scan.blocked_event_ids,
            "forbidden_uses_enforced": [
                "audit_export",
                "compliance_evidence",
                "cross_system_trust_decision",
                "external_reporting"
            ],
        });
        if output::json_enabled() {
            let envelope = Envelope::new("cortex.audit.export", Exit::Ok, artifact)
                .with_policy_outcome(policy_outcome_summary(&policy));
            output::emit(&envelope, Exit::Ok)
        } else {
            match serde_json::to_string_pretty(&artifact) {
                Ok(serialized) => {
                    println!("{serialized}");
                    Exit::Ok
                }
                Err(err) => {
                    eprintln!("audit export: failed to serialize artifact: {err}");
                    Exit::Internal
                }
            }
        }
    } else {
        eprintln!(
            "audit export: ledger rows cannot be used for {}; \
             rerun with --local-diagnostic for local diagnostics only",
            args.surface.label()
        );
        export_failure_envelope(
            Exit::PreconditionUnmet,
            &format!(
                "ledger rows cannot be used for {}; rerun with --local-diagnostic",
                args.surface.label()
            ),
            Some(&policy),
        )
    }
}

/// Compose the ADR 0026 policy decision for the audit export surface.
///
/// Contributors:
/// - `audit.export.development_ledger`: `Reject` when the requested surface
///   would consume development-ledger rows in a non-diagnostic mode and the
///   row scan flagged any blocked event ids.
/// - `audit.export.signed_local_class`: `Reject` when a non-default external
///   authority surface is requested and there is no externally anchored
///   evidence available (current local-only path never has it).
/// - `audit.export.proof_closure`: `Quarantine` because the local
///   development ledger only provides `ClaimProofState::Partial` until the
///   signed/anchored chain landings — proof closure cannot promote.
/// - `audit.export.temporal_authority`: Phase 2.6 T3 closure — weakest-link
///   compose across the distinct signing `key_id`s observed in the row
///   set via [`AuthorityRepo::revalidate`](cortex_store::repo::AuthorityRepo).
fn compose_export_policy_decision(
    scan: &LedgerAuthorityScan,
    surface: AuditExportSurface,
    local_diagnostic: bool,
    temporal_authority: PolicyContribution,
) -> PolicyDecision {
    let development_outcome = if scan.blocked_event_ids.is_empty() {
        PolicyOutcome::Allow
    } else if local_diagnostic {
        // Diagnostic mode tolerates blocked rows; the artifact must
        // still carry forbidden_uses (handled at the artifact layer).
        PolicyOutcome::Warn
    } else {
        PolicyOutcome::Reject
    };
    let development_reason = match development_outcome {
        PolicyOutcome::Allow => {
            "no development-ledger rows are blocked for the requested surface".to_string()
        }
        PolicyOutcome::Warn => format!(
            "{} development-ledger rows are blocked but local diagnostic mode tolerates them",
            scan.blocked_event_ids.len()
        ),
        _ => format!(
            "{} development-ledger rows are forbidden for {}",
            scan.blocked_event_ids.len(),
            surface.label()
        ),
    };

    // `audit.export.signed_local_class` — non-default surfaces require
    // external authority; the local-unsigned ledger never qualifies. The
    // default surface and `--local-diagnostic` mode both stay
    // diagnostic-only and therefore compose `Warn`.
    let signed_local_outcome = if surface.is_default_audit_export() || local_diagnostic {
        PolicyOutcome::Warn
    } else {
        PolicyOutcome::Reject
    };
    let signed_local_reason = match signed_local_outcome {
        PolicyOutcome::Warn => {
            "local-unsigned ledger is diagnostic-only and cannot promote authority".to_string()
        }
        _ => format!(
            "{} requires external authority class which is not available from local-unsigned ledger",
            surface.label()
        ),
    };

    // `audit.export.proof_closure` — the development ledger provides at
    // most `Partial` proof state. ADR 0036 says `Partial` quarantines
    // authority claims; the diagnostic mode keeps that Quarantine visible
    // rather than softening it to `Warn`.
    let proof_outcome = PolicyOutcome::Quarantine;
    let proof_reason =
        "proof state is Partial; ADR 0036 forbids promoting partial-proof artifacts".to_string();

    let contributions = vec![
        PolicyContribution::new(
            EXPORT_DEVELOPMENT_LEDGER_RULE_ID,
            development_outcome,
            development_reason,
        )
        .expect("export development-ledger contribution is statically valid"),
        PolicyContribution::new(
            EXPORT_SIGNED_LOCAL_CLASS_RULE_ID,
            signed_local_outcome,
            signed_local_reason,
        )
        .expect("export signed-local class contribution is statically valid"),
        PolicyContribution::new(EXPORT_PROOF_CLOSURE_RULE_ID, proof_outcome, proof_reason)
            .expect("export proof-closure contribution is statically valid"),
        temporal_authority,
    ];
    compose_policy_outcomes(contributions, None)
}

fn export_failure_envelope(exit: Exit, detail: &str, policy: Option<&PolicyDecision>) -> Exit {
    if !output::json_enabled() {
        return exit;
    }
    let payload = match policy {
        Some(policy) => serde_json::json!({
            "status": "error",
            "detail": detail,
            "policy_outcome": policy.final_outcome,
            "policy_contributing": policy.contributing,
            "policy_discarded": policy.discarded,
        }),
        None => serde_json::json!({
            "status": "error",
            "detail": detail,
        }),
    };
    let envelope = match policy {
        Some(policy) => Envelope::new("cortex.audit.export", exit, payload)
            .with_policy_outcome(policy_outcome_summary(policy)),
        None => Envelope::new("cortex.audit.export", exit, payload),
    };
    output::emit(&envelope, exit)
}

fn print_report(report: &Report) {
    let json = output::json_enabled();
    if !json {
        println!(
            "audit verify: {} ({} rows scanned, {} failures)",
            report.path.display(),
            report.rows_scanned,
            report.failures.len(),
        );
    }
    let mut failures = Vec::new();
    for f in &report.failures {
        let line = f.line;
        let reason = &f.reason;
        let invariant = reason
            .invariant()
            .map(|name| format!(" invariant={name}"))
            .unwrap_or_default();
        if !json {
            match &f.event_id {
                Some(id) => eprintln!("  line {line} event_id={id}{invariant}: {reason:?}"),
                None => eprintln!("  line {line}{invariant}: {reason:?}"),
            }
        }
        failures.push(VerifyFailure {
            line,
            event_id: f.event_id.as_ref().map(ToString::to_string),
            invariant: reason.invariant().map(str::to_string),
            reason: format!("{reason:?}"),
        });
    }
    if json {
        VERIFY_REPORT.with(|cell| {
            let mut report_ref = cell.borrow_mut();
            let entry = report_ref.get_or_insert_with(VerifyReport::default);
            entry.path = Some(report.path.display().to_string());
            entry.rows_scanned = report.rows_scanned;
            entry.chain_ok = report.ok();
            entry.failures = failures;
        });
    }
}

thread_local! {
    static VERIFY_REPORT: std::cell::RefCell<Option<VerifyReport>> =
        const { std::cell::RefCell::new(None) };
    // Per-invocation accumulator of ADR 0026 contributor outcomes for the
    // `cortex audit verify` surface. Reset at the top of each `run_verify`
    // call and drained once the inner pipeline returns.
    static VERIFY_CONTRIBUTIONS: std::cell::RefCell<Vec<PolicyContribution>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

/// Phase 2.6 closure: append a typed `audit.verify.temporal_authority`
/// contributor for the `cortex audit verify --signed` surface using
/// `AuthorityRepo::revalidate` against the durable
/// `authority_key_timeline`. `minimum_trust_tier = Verified` per audit
/// §6.2 (signed-chain audit inherits the chain's minimum tier).
///
/// Failure modes:
///
/// - Store cannot be opened (no `cortex init` in scope) — emit
///   `Reject` with the stable invariant.
/// - `AuthorityRepo::revalidate` SQL failure — emit `Reject`.
/// - Revalidation reports `Quarantine` / `Reject` — emit that outcome
///   with the per-reason wire strings so the operator transcript
///   names the failing edge.
///
/// On success emits `Allow` so the composed verify policy keeps the
/// contributor present (ADR 0026 §2 composition requires the
/// contributor to be observed, not absent).
fn record_temporal_authority_contribution_for_audit_verify(key_id: &str) {
    let invariant = revalidation_failed_invariant("audit.verify");
    let pool = match open_default_store("audit verify") {
        Ok(pool) => pool,
        Err(_) => {
            record_verify_contribution(
                VERIFY_TEMPORAL_AUTHORITY_RULE_ID,
                PolicyOutcome::Reject,
                &format!(
                    "{invariant}: cannot open default store to revalidate operator key {key_id}"
                ),
            );
            return;
        }
    };
    let now = chrono::Utc::now();
    match revalidate_operator_temporal_authority(
        &pool,
        VERIFY_TEMPORAL_AUTHORITY_RULE_ID,
        key_id,
        now,
        TrustTier::Verified,
    ) {
        Ok(contribution) => {
            let outcome = contribution.outcome();
            let reason = if contribution.report.valid_now {
                format!(
                    "operator temporal authority valid for current use (key {})",
                    contribution.report.key_id,
                )
            } else {
                let reasons = contribution
                    .report
                    .reasons
                    .iter()
                    .map(|reason| reason.wire_str())
                    .collect::<Vec<_>>()
                    .join(",");
                format!(
                    "{invariant}: operator temporal authority current use blocked for key {} (reasons: {reasons})",
                    contribution.report.key_id,
                )
            };
            record_verify_contribution(VERIFY_TEMPORAL_AUTHORITY_RULE_ID, outcome, &reason);
        }
        Err(err) => {
            record_verify_contribution(
                VERIFY_TEMPORAL_AUTHORITY_RULE_ID,
                PolicyOutcome::Reject,
                &format!("{invariant}: failed to read authority timeline for key {key_id}: {err}"),
            );
        }
    }
}

fn record_verify_contribution(rule_id: &'static str, outcome: PolicyOutcome, reason: &str) {
    let Ok(contribution) = PolicyContribution::new(rule_id, outcome, reason) else {
        // PolicyContribution::new only rejects empty rule ids / reasons;
        // both inputs are compile-time constants and operator-facing
        // strings, so a failure here would be a programmer error. Skip
        // the contribution rather than panic to keep verification
        // observable even when a future caller forgets a reason.
        return;
    };
    VERIFY_CONTRIBUTIONS.with(|cell| cell.borrow_mut().push(contribution));
}

/// Scan the JSONL event log at `path` for the distinct set of signing
/// `key_id`s observed across signed rows. Returns the empty set when the
/// log is unsigned (no row carries a [`cortex_ledger::signed_row::RowSignature`])
/// or when the log is empty.
///
/// Used by the Phase 2.6 T3 contributors for `cortex audit export` and
/// `cortex audit anchor`: each surface revalidates the aggregate of
/// distinct keys observed across the row set against the durable
/// `authority_key_timeline`, weakest-link composing the per-key outcomes
/// into a single `audit.export.temporal_authority` /
/// `audit.anchor.temporal_authority` contributor.
fn scan_signed_row_key_ids(path: &PathBuf) -> Result<Vec<String>, JsonlError> {
    let log = JsonlLog::open(path)?;
    let mut seen: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for item in log.iter_signed()? {
        let row = match item {
            Ok(r) => r,
            // Skip decode errors here — the temporal-authority axis is
            // composed alongside the chain-corruption axis at the
            // surface; bubbling the JSONL error from this helper would
            // mask the row that failed to parse.
            Err(_) => continue,
        };
        if let Some(sig) = row.signature.as_ref() {
            seen.insert(sig.key_id.clone());
        }
    }
    Ok(seen.into_iter().collect())
}

/// Phase 2.6 T3 closure: weakest-link compose a typed temporal-authority
/// contributor across the set of distinct signing `key_id`s observed in
/// the row set of the JSONL log at `path`.
///
/// This is the shared building block for `cortex audit export` and
/// `cortex audit anchor`. Per audit §6.2 both surfaces use
/// `minimum_trust_tier = TrustTier::Verified` (default surface). Failure
/// modes:
///
/// - JSONL scan error: emit `Reject` with the stable invariant
///   `{surface}.operator_temporal_authority.revalidation_failed`.
/// - Cannot open store: emit `Reject` with the stable invariant.
/// - Any per-key revalidation returns `Quarantine` / `Reject`: emit that
///   outcome (weakest-link compose).
/// - No signed rows in the log: emit `Warn` "no signed rows; no temporal
///   axis to evaluate" so the contributor is still observable in the
///   composed report (ADR 0026 §2 requires the axis to be observed, not
///   absent).
/// - Per-key revalidation `Allow` across all keys: emit `Allow`.
fn build_temporal_authority_contribution_for_row_set(
    path: &PathBuf,
    surface: &str,
    rule_id: &'static str,
) -> PolicyContribution {
    let invariant = revalidation_failed_invariant(surface);
    let key_ids = match scan_signed_row_key_ids(path) {
        Ok(keys) => keys,
        Err(err) => {
            return PolicyContribution::new(
                rule_id,
                PolicyOutcome::Reject,
                format!("{invariant}: failed to scan signed rows for key_ids: {err}"),
            )
            .expect("static rule id + non-empty reason is valid");
        }
    };
    if key_ids.is_empty() {
        // No signed rows: the row set carries no temporal axis to
        // evaluate. Emit `Warn` so the contributor is present in the
        // composed decision without claiming the axis was verified.
        return PolicyContribution::new(
            rule_id,
            PolicyOutcome::Warn,
            "no signed rows present in row set; no temporal authority axis to revalidate",
        )
        .expect("static rule id + non-empty reason is valid");
    }
    let pool = match open_default_store(surface) {
        Ok(pool) => pool,
        Err(_) => {
            return PolicyContribution::new(
                rule_id,
                PolicyOutcome::Reject,
                format!(
                    "{invariant}: cannot open default store to revalidate {} operator key(s)",
                    key_ids.len(),
                ),
            )
            .expect("static rule id + non-empty reason is valid");
        }
    };
    let now = chrono::Utc::now();
    let mut worst_outcome = PolicyOutcome::Allow;
    let mut failing_reasons: Vec<String> = Vec::new();
    let mut allowed_keys: Vec<String> = Vec::new();
    for key_id in &key_ids {
        match revalidate_operator_temporal_authority(
            &pool,
            rule_id,
            key_id,
            now,
            TrustTier::Verified,
        ) {
            Ok(contribution) => {
                let outcome = contribution.outcome();
                if contribution.report.valid_now {
                    allowed_keys.push(contribution.report.key_id.clone());
                } else {
                    let reasons = contribution
                        .report
                        .reasons
                        .iter()
                        .map(|reason| reason.wire_str())
                        .collect::<Vec<_>>()
                        .join(",");
                    failing_reasons.push(format!(
                        "key {} -> {outcome:?} (reasons: {reasons})",
                        contribution.report.key_id,
                    ));
                }
                if temporal_outcome_rank(outcome) > temporal_outcome_rank(worst_outcome) {
                    worst_outcome = outcome;
                }
            }
            Err(err) => {
                failing_reasons.push(format!("key {key_id} -> Reject (store error: {err})"));
                worst_outcome = PolicyOutcome::Reject;
            }
        }
    }
    let reason = if matches!(worst_outcome, PolicyOutcome::Allow) {
        format!(
            "operator temporal authority valid for current use across {} observed key(s): {}",
            allowed_keys.len(),
            allowed_keys.join(","),
        )
    } else {
        format!(
            "{invariant}: operator temporal authority current use blocked for {} of {} observed key(s); {}",
            failing_reasons.len(),
            key_ids.len(),
            failing_reasons.join("; "),
        )
    };
    PolicyContribution::new(rule_id, worst_outcome, reason)
        .expect("static rule id + non-empty reason is valid")
}

/// Weakest-link rank for [`PolicyOutcome`] in the Phase 2.6 T3 temporal
/// authority contributor composition. Higher rank = "worse" = wins the
/// composition. Mirrors `PolicyOutcome::weakest` semantics restricted to
/// the variants this contributor produces (Allow / Warn / Quarantine /
/// Reject; BreakGlass does not arise from `AuthorityRepo::revalidate`).
fn temporal_outcome_rank(outcome: PolicyOutcome) -> u8 {
    match outcome {
        PolicyOutcome::Allow => 0,
        PolicyOutcome::Warn => 1,
        PolicyOutcome::Quarantine => 2,
        PolicyOutcome::Reject => 3,
        PolicyOutcome::BreakGlass => 1,
    }
}

fn compose_verify_policy_decision() -> (PolicyDecision, ProofClosureReport) {
    let contributions = VERIFY_CONTRIBUTIONS.with(|cell| std::mem::take(&mut *cell.borrow_mut()));
    if contributions.is_empty() {
        // Defensive fallback: `run_verify_inner` should always record at
        // least the hash-chain contributor. If the function bailed out
        // before recording (clap usage error, unmet precondition), surface
        // an explicit `Reject` so a JSON consumer cannot misread silence
        // as `Allow`.
        let fallback = PolicyContribution::new(
            VERIFY_HASH_CHAIN_CLOSURE_RULE_ID,
            PolicyOutcome::Reject,
            "audit verify bailed out before recording any contributor",
        )
        .expect("static fallback contribution is valid");
        let decision = compose_policy_outcomes(vec![fallback.clone()], None);
        let report = compose_verify_proof_closure_report(std::slice::from_ref(&fallback));
        return (decision, report);
    }
    let report = compose_verify_proof_closure_report(&contributions);
    let decision = compose_policy_outcomes(contributions, None);
    (decision, report)
}

/// Fold the three `audit verify` axis contributors into a single typed
/// [`ProofClosureReport`].
///
/// ADR 0036 composition rule: hash-chain Reject collapses the whole report
/// to [`ProofState::Broken`] regardless of the other axes; otherwise the
/// weakest truthful state is derived from the failing edges across all
/// observed axes. Each contributor maps to one `ProofEdgeKind` so a JSON
/// consumer can see which axis produced the failure:
///
/// - [`VERIFY_HASH_CHAIN_CLOSURE_RULE_ID`] -> [`ProofEdgeKind::HashChain`]
/// - [`VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID`] -> [`ProofEdgeKind::Signature`]
/// - [`VERIFY_V1_TO_V2_BOUNDARY_RULE_ID`] -> [`ProofEdgeKind::HashChain`]
///   (the v1→v2 boundary is itself a hash-chain invariant landing at the
///   schema migration boundary; ADR 0036 §2 allows the schema axis to ride
///   the existing variants).
///
/// The stable invariant
/// [`VERIFY_PROOF_CLOSURE_COMPOSED_REPORT_INVARIANT`] documents this fold
/// for downstream consumers.
fn compose_verify_proof_closure_report(contributions: &[PolicyContribution]) -> ProofClosureReport {
    let mut verified_edges: Vec<ProofEdge> = Vec::new();
    let mut failing_edges: Vec<FailingEdge> = Vec::new();
    let mut hash_chain_rejected = false;

    for contribution in contributions {
        let rule_id = contribution.rule_id.as_str();
        let (kind, axis_label) = match rule_id {
            VERIFY_HASH_CHAIN_CLOSURE_RULE_ID => (ProofEdgeKind::HashChain, "hash_chain_closure"),
            VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID => {
                (ProofEdgeKind::Signature, "signed_chain_closure")
            }
            VERIFY_V1_TO_V2_BOUNDARY_RULE_ID => (ProofEdgeKind::HashChain, "v1_to_v2_boundary"),
            _ => continue,
        };

        match contribution.outcome {
            PolicyOutcome::Allow => {
                verified_edges.push(
                    ProofEdge::new(kind, "audit.verify", axis_label)
                        .with_evidence_ref(rule_id.to_string()),
                );
            }
            PolicyOutcome::Reject => {
                if matches!(rule_id, VERIFY_HASH_CHAIN_CLOSURE_RULE_ID) {
                    hash_chain_rejected = true;
                }
                failing_edges.push(FailingEdge::broken(
                    kind,
                    "audit.verify",
                    axis_label,
                    ProofEdgeFailure::Mismatch,
                    contribution.reason.as_str(),
                ));
            }
            PolicyOutcome::Quarantine => failing_edges.push(FailingEdge::unresolved(
                kind,
                "audit.verify",
                contribution.reason.as_str(),
            )),
            PolicyOutcome::Warn | PolicyOutcome::BreakGlass => failing_edges.push(
                FailingEdge::unresolved(kind, "audit.verify", contribution.reason.as_str()),
            ),
        }
    }

    // Composition rule: hash-chain Reject collapses the whole report to
    // Broken. `ProofClosureReport::from_edges` already classifies any broken
    // failing edge as `ProofState::Broken`, so the
    // `FailingEdge::broken(..)` above is sufficient — the explicit flag is
    // retained for the unit test contract and to document intent.
    let _ = hash_chain_rejected;
    ProofClosureReport::from_edges(verified_edges, failing_edges)
}

/// Shared helper: serialise a [`PolicyDecision`] into the JSON envelope
/// `policy_outcome` field shape. Mirrors the convention used by the other
/// ADR 0026 surfaces (`cortex release readiness`, `cortex compliance
/// evidence`, etc.).
fn policy_outcome_summary(policy: &PolicyDecision) -> serde_json::Value {
    serde_json::json!({
        "final_outcome": policy.final_outcome,
        "contributing": policy.contributing,
        "discarded": policy.discarded,
    })
}

fn record_verify_policy_decision(policy: &PolicyDecision) {
    if !output::json_enabled() {
        return;
    }
    VERIFY_REPORT.with(|cell| {
        let mut r = cell.borrow_mut();
        let entry = r.get_or_insert_with(VerifyReport::default);
        entry.policy_outcome = Some(VerifyPolicyOutcome::from_decision(policy));
    });
}

fn record_verify_proof_closure(report: &ProofClosureReport) {
    if !output::json_enabled() {
        return;
    }
    VERIFY_REPORT.with(|cell| {
        let mut r = cell.borrow_mut();
        let entry = r.get_or_insert_with(VerifyReport::default);
        entry.proof_closure = Some(report.clone());
    });
}

fn print_verify_proof_closure(report: &ProofClosureReport) {
    if output::json_enabled() {
        return;
    }
    let state = report.state();
    let invariant = VERIFY_PROOF_CLOSURE_COMPOSED_REPORT_INVARIANT;
    eprintln!("audit verify: invariant={invariant} proof_state={state:?}");
    for failing in report.failing_edges() {
        let kind = failing.kind;
        let from_ref = &failing.from_ref;
        let failure = failing.failure;
        let reason = &failing.reason;
        eprintln!(
            "audit verify: invariant={invariant} failing_edge kind={kind:?} from={from_ref} failure={failure:?} reason={reason}"
        );
    }
}

fn print_verify_policy_outcome(policy: &PolicyDecision) {
    if output::json_enabled() {
        return;
    }
    let final_outcome = policy.final_outcome;
    eprintln!("audit verify: policy_outcome={final_outcome:?}");
    for contribution in &policy.contributing {
        let outcome = contribution.outcome;
        let rule_id = contribution.rule_id.as_str();
        let reason = contribution.reason.as_str();
        eprintln!(
            "audit verify: policy_contributing={rule_id} outcome={outcome:?} reason={reason}"
        );
    }
    for contribution in &policy.discarded {
        let outcome = contribution.outcome;
        let rule_id = contribution.rule_id.as_str();
        let reason = contribution.reason.as_str();
        eprintln!("audit verify: policy_discarded={rule_id} outcome={outcome:?} reason={reason}");
    }
}

#[derive(Debug, Serialize)]
struct VerifyReport {
    #[serde(skip_serializing_if = "Option::is_none")]
    path: Option<String>,
    rows_scanned: usize,
    chain_ok: bool,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    failures: Vec<VerifyFailure>,
    #[serde(skip_serializing_if = "Option::is_none")]
    boundary: Option<BoundaryReport>,
    #[serde(skip_serializing_if = "Option::is_none")]
    anchor: Option<AnchorMatch>,
    #[serde(skip_serializing_if = "Option::is_none")]
    anchor_history: Option<AnchorHistoryMatch>,
    #[serde(skip_serializing_if = "Option::is_none")]
    external_receipts: Option<ExternalReceiptsMatch>,
    #[serde(skip_serializing_if = "Option::is_none")]
    signed_verification: Option<SignedVerification>,
    /// Composed ADR 0026 policy outcome over the verify-side contributors.
    /// Mirrors the `policy_outcome` envelope field so the structured report
    /// is internally consistent with the top-level envelope.
    #[serde(skip_serializing_if = "Option::is_none")]
    policy_outcome: Option<VerifyPolicyOutcome>,
    /// Composed ADR 0036 proof closure report for the verify pass.
    ///
    /// Folds the per-axis contributors
    /// ([`VERIFY_HASH_CHAIN_CLOSURE_RULE_ID`],
    /// [`VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID`],
    /// [`VERIFY_V1_TO_V2_BOUNDARY_RULE_ID`]) into a single typed
    /// [`ProofClosureReport`] so the verify surface can return one
    /// ADR 0036 three-valued result. The per-contributor entries on
    /// `policy_outcome` are kept as-is for ADR 0026 explainability.
    #[serde(skip_serializing_if = "Option::is_none")]
    proof_closure: Option<ProofClosureReport>,
    /// ADR 0037 truth-ceiling triad. `cortex audit verify` is a local
    /// diagnostic surface that does not promote claims, so the
    /// fail-closed default is `local_unsigned` runtime mode with proof
    /// state mirroring the observed chain state. Operators reading the
    /// JSON envelope offline can grep these fields to recompute the
    /// truth ceiling without re-running the command.
    runtime_mode: RuntimeMode,
    proof_state: ClaimProofState,
    claim_ceiling: ClaimCeiling,
    authority_class: AuthorityClass,
}

impl Default for VerifyReport {
    fn default() -> Self {
        // Fail-closed defaults for `audit verify`: until the inner
        // verification path observes the chain, we cannot promote
        // claims above local_unsigned mechanics. The triad is
        // refined when `run_verify_inner` observes the actual
        // chain/signature state.
        Self {
            path: None,
            rows_scanned: 0,
            chain_ok: false,
            failures: Vec::new(),
            boundary: None,
            anchor: None,
            anchor_history: None,
            external_receipts: None,
            signed_verification: None,
            policy_outcome: None,
            proof_closure: None,
            runtime_mode: RuntimeMode::LocalUnsigned,
            proof_state: ClaimProofState::Unknown,
            claim_ceiling: ClaimCeiling::DevOnly,
            authority_class: AuthorityClass::Observed,
        }
    }
}

#[derive(Debug, Serialize)]
struct VerifyPolicyOutcome {
    final_outcome: PolicyOutcome,
    contributing: Vec<PolicyContribution>,
    discarded: Vec<PolicyContribution>,
}

impl VerifyPolicyOutcome {
    fn from_decision(policy: &PolicyDecision) -> Self {
        Self {
            final_outcome: policy.final_outcome,
            contributing: policy.contributing.clone(),
            discarded: policy.discarded.clone(),
        }
    }
}

impl VerifyReport {
    fn take_or_default(cell: &std::cell::RefCell<Option<Self>>) -> Self {
        cell.borrow_mut().take().unwrap_or_default()
    }
}

#[derive(Debug, Serialize)]
struct VerifyFailure {
    line: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    event_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    invariant: Option<String>,
    reason: String,
}

#[derive(Debug, Serialize)]
struct BoundaryReport {
    required: bool,
    ok: bool,
    failures: Vec<String>,
}

#[derive(Debug, Serialize)]
struct AnchorMatch {
    anchor_path: String,
    event_count: u64,
    db_count: u64,
}

#[derive(Debug, Serialize)]
struct AnchorHistoryMatch {
    history_path: String,
    anchors_verified: usize,
    latest_event_count: u64,
    db_count: u64,
}

#[derive(Debug, Serialize)]
struct ExternalReceiptsMatch {
    receipts_path: String,
    receipts_verified: usize,
    latest_anchor_event_count: u64,
    db_count: u64,
    /// Surface the deferred-authority status verbatim so a JSON consumer
    /// sees the same `parsed_only_signature_verification_pending` token
    /// that the prose output emits — this is the truth-ceiling guardrail
    /// for the external receipt verifier.
    external_anchor_authority: &'static str,
    status: String,
    /// Provenance token for the trusted root in force during this verify
    /// pass: either `embedded_snapshot` or `operator_cached`.
    trust_root_status: &'static str,
    /// Activation timestamp of the trusted root in force, RFC 3339.
    #[serde(skip_serializing_if = "Option::is_none")]
    trust_root_signed_at: Option<String>,
}

/// Resolve the default `trusted_root.json` cache path: `<data_dir>/trusted_root.json`.
///
/// Returns `None` when the data directory cannot be resolved (degenerate
/// environments without `$HOME`/XDG vars). In that case the verifier
/// falls back to the embedded snapshot.
pub(crate) fn trust_root_cache_path() -> Option<PathBuf> {
    crate::paths::default_data_dir().map(|d| d.join("trusted_root.json"))
}

#[derive(Debug, Serialize)]
struct SignedVerification {
    key_id: String,
}

#[derive(Debug, Default)]
struct LedgerAuthorityScan {
    blocked_event_ids: Vec<String>,
}

fn scan_development_ledger_rows(
    path: &PathBuf,
    requested_use: DevelopmentLedgerUse,
) -> Result<LedgerAuthorityScan, JsonlError> {
    let log = JsonlLog::open(path)?;
    let mut scan = LedgerAuthorityScan::default();
    for event in log.iter()? {
        let event = event?;
        let decision = development_ledger_use_decision(&event.payload, requested_use);
        if !decision.allowed {
            scan.blocked_event_ids.push(event.id.to_string());
        }
    }
    Ok(scan)
}

fn load_attestor_from_key_file(path: &PathBuf) -> Result<InMemoryAttestor, Exit> {
    let bytes = std::fs::read(path).map_err(|err| {
        eprintln!(
            "audit verify: cannot read --attestation key file `{}`: {err}",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    if bytes.len() != 32 {
        eprintln!(
            "audit verify: --attestation key file `{}` must be exactly 32 raw bytes (Ed25519 seed); got {} bytes",
            path.display(),
            bytes.len()
        );
        return Err(Exit::PreconditionUnmet);
    }
    let mut seed = [0u8; 32];
    seed.copy_from_slice(&bytes);
    Ok(InMemoryAttestor::from_seed(&seed))
}

fn load_verifying_key_from_file(path: &PathBuf) -> Result<(VerifyingKey, String), Exit> {
    let bytes = std::fs::read(path).map_err(|err| {
        eprintln!(
            "audit verify: cannot read --verification-key file `{}`: {err}",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    let key_bytes: [u8; 32] = match bytes.as_slice().try_into() {
        Ok(key_bytes) => key_bytes,
        Err(_) => {
            eprintln!(
                "audit verify: --verification-key file `{}` must be exactly 32 raw bytes (Ed25519 public key); got {} bytes",
                path.display(),
                bytes.len()
            );
            return Err(Exit::PreconditionUnmet);
        }
    };
    let verifying_key = VerifyingKey::from_bytes(&key_bytes).map_err(|err| {
        eprintln!(
            "audit verify: --verification-key file `{}` is not a valid Ed25519 public key: {err}",
            path.display()
        );
        Exit::PreconditionUnmet
    })?;
    Ok((verifying_key, hex_lower(&key_bytes)))
}

fn hex_lower(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        out.push(HEX[(b >> 4) as usize] as char);
        out.push(HEX[(b & 0x0f) as usize] as char);
    }
    out
}

// =============================================================================
// `cortex audit refresh-trust` — TUF-rooted Rekor trust-bundle refresh
// =============================================================================

/// Default URL the refresh fetches from. The published Sigstore CDN ships
/// `trusted_root.json` under a content-addressed path; rolling URLs are
/// resolved by the operator via `--url <URL>` when needed (e.g. mirroring).
pub const DEFAULT_TRUSTED_ROOT_URL: &str =
    "https://tuf-repo-cdn.sigstore.dev/targets/trusted_root.json";

/// Stable command name surfaced on the JSON envelope.
pub const REFRESH_TRUST_COMMAND_NAME: &str = "cortex.audit.anchor.refresh_trust";

/// Stable outcome token: refresh succeeded; cached root was newer than
/// the previous cached root.
pub const REFRESH_TRUST_OUTCOME_OK: &str = "ok";
/// Stable outcome token: the HTTP fetch failed (network unavailable, 4xx /
/// 5xx response, mirror misconfigured).
pub const REFRESH_TRUST_OUTCOME_HTTP_ERROR: &str = "http_error";
/// Stable outcome token: the fetched payload did not parse as a Sigstore
/// trust root.
pub const REFRESH_TRUST_OUTCOME_PARSE_ERROR: &str = "parse_error";
/// Stable outcome token: the fetched root structurally validated but
/// failed the chain-of-trust check against the embedded snapshot's
/// schema invariants. Reserved for the cryptographic signature check
/// that lands in a follow-on slice.
pub const REFRESH_TRUST_OUTCOME_SIGNATURE_INVALID: &str = "signature_invalid";
/// Stable outcome token: the fetched root parsed but was no fresher
/// than the cached root and the cached root itself is still stale.
/// Operators see this when their TUF mirror has not yet refreshed.
pub const REFRESH_TRUST_OUTCOME_STALE_TO_STALE: &str = "stale_to_stale";

/// Stable invariant name emitted alongside each outcome token; these are
/// the canonical dotted-namespace identifiers per the council Decision #1
/// doctrine guardrail.
pub const REFRESH_TRUST_INVARIANT_OK: &str = "audit.anchor.refresh_trust.ok";
/// Stable invariant: HTTP/network fetch failed.
pub const REFRESH_TRUST_INVARIANT_HTTP_ERROR: &str = "audit.anchor.refresh_trust.http_error";
/// Stable invariant: fetched payload did not parse.
pub const REFRESH_TRUST_INVARIANT_PARSE_ERROR: &str = "audit.anchor.refresh_trust.parse_error";
/// Stable invariant: fetched root failed a structural chain-of-trust
/// check against the embedded snapshot (e.g. activation regression).
pub const REFRESH_TRUST_INVARIANT_SIGNATURE_INVALID: &str =
    "audit.anchor.refresh_trust.signature_invalid";
/// Stable invariant: fetched root was not newer than the cached root.
pub const REFRESH_TRUST_INVARIANT_STALE_TO_STALE: &str =
    "audit.anchor.refresh_trust.stale_to_stale";

const fn invariant_for_outcome(outcome: &str) -> &'static str {
    match outcome.as_bytes() {
        b"ok" => REFRESH_TRUST_INVARIANT_OK,
        b"http_error" => REFRESH_TRUST_INVARIANT_HTTP_ERROR,
        b"parse_error" => REFRESH_TRUST_INVARIANT_PARSE_ERROR,
        b"signature_invalid" => REFRESH_TRUST_INVARIANT_SIGNATURE_INVALID,
        b"stale_to_stale" => REFRESH_TRUST_INVARIANT_STALE_TO_STALE,
        // Future outcomes default to the generic namespace prefix so a
        // forgotten arm is still observable rather than silently
        // emitting the bare token.
        _ => "audit.anchor.refresh_trust.unknown",
    }
}

/// `cortex audit refresh-trust` flags.
#[derive(Debug, Args)]
pub struct RefreshTrustArgs {
    /// URL of the upstream `trusted_root.json`. Defaults to the Sigstore
    /// public TUF CDN.
    #[arg(long = "url", value_name = "URL")]
    pub url: Option<String>,

    /// Path of the on-disk cache to install. Defaults to
    /// `<data_dir>/trusted_root.json`.
    #[arg(long = "cache-path", value_name = "PATH")]
    pub cache_path: Option<PathBuf>,
}

/// Structured report for the JSON envelope; fields are part of the CLI
/// contract.
#[derive(Debug, Default, Serialize)]
struct RefreshTrustReport {
    /// `cortex.audit.anchor.refresh_trust` command identifier.
    command: &'static str,
    /// Stable outcome token from the `REFRESH_TRUST_OUTCOME_*` set.
    outcome: &'static str,
    /// Stable dotted-namespace invariant for this outcome
    /// (`audit.anchor.refresh_trust.*`).
    invariant: &'static str,
    /// URL actually fetched.
    url: String,
    /// Cache path actually written / inspected.
    cache_path: String,
    /// `validFor.start` of the cached root before the refresh, when one
    /// was present.
    #[serde(skip_serializing_if = "Option::is_none")]
    previous_signed_at: Option<DateTime<Utc>>,
    /// `validFor.start` of the fetched root, when it parsed.
    #[serde(skip_serializing_if = "Option::is_none")]
    new_signed_at: Option<DateTime<Utc>>,
    /// Whether the cache file on disk changed.
    cache_written: bool,
    /// Human-readable failure summary on non-Ok outcomes.
    #[serde(skip_serializing_if = "Option::is_none")]
    failure_reason: Option<String>,
}

/// Run `cortex audit refresh-trust`.
pub fn run_refresh_trust(args: RefreshTrustArgs) -> Exit {
    let mut report = RefreshTrustReport {
        command: REFRESH_TRUST_COMMAND_NAME,
        outcome: REFRESH_TRUST_OUTCOME_OK,
        invariant: REFRESH_TRUST_INVARIANT_OK,
        ..Default::default()
    };
    let exit = run_refresh_trust_inner(args, &mut report);
    // Sync invariant to whatever the inner pipeline ended up setting.
    report.invariant = invariant_for_outcome(report.outcome);
    if !output::json_enabled() {
        eprintln!("audit refresh-trust: invariant={}", report.invariant);
    }
    if output::json_enabled() {
        let outcome_token = match exit {
            Exit::Ok => crate::output::Outcome::Ok,
            Exit::PreconditionUnmet => crate::output::Outcome::PreconditionUnmet,
            Exit::Internal => crate::output::Outcome::Internal,
            other => crate::output::Outcome::from_exit(other),
        };
        let envelope =
            Envelope::new(REFRESH_TRUST_COMMAND_NAME, exit, report).with_outcome(outcome_token);
        output::emit(&envelope, exit)
    } else {
        exit
    }
}

fn run_refresh_trust_inner(args: RefreshTrustArgs, report: &mut RefreshTrustReport) -> Exit {
    let url = args
        .url
        .unwrap_or_else(|| DEFAULT_TRUSTED_ROOT_URL.to_string());
    let cache_path = match args.cache_path {
        Some(path) => path,
        None => match crate::paths::default_data_dir() {
            Some(dir) => dir.join("trusted_root.json"),
            None => {
                eprintln!(
                    "audit refresh-trust: no data directory could be resolved; pass --cache-path to override"
                );
                report.outcome = REFRESH_TRUST_OUTCOME_HTTP_ERROR;
                report.url = url;
                report.cache_path = String::from("<unresolved>");
                report.failure_reason =
                    Some("default data directory unresolved; supply --cache-path".into());
                return Exit::PreconditionUnmet;
            }
        },
    };
    report.url = url.clone();
    report.cache_path = cache_path.display().to_string();

    // Inspect the previously cached root so the envelope can report the
    // pre-refresh activation date. Missing cache is fine: the embedded
    // root is the floor and the refresh installs a real cache.
    let previous_signed_at = match TrustedRoot::load_cached(&cache_path) {
        Ok(Some(previous)) => previous.metadata_signed_at(),
        Ok(None) => None,
        Err(err) => {
            // A cache file exists but did not parse. The refresh path
            // is still allowed to overwrite, but we report the parse
            // outcome so the operator sees that the old cache was
            // garbage. We do not fail closed here — the whole point of
            // refresh-trust is to recover from a broken cache.
            eprintln!(
                "audit refresh-trust: existing cache `{}` did not parse and will be replaced: {err}",
                cache_path.display()
            );
            None
        }
    };
    report.previous_signed_at = previous_signed_at;

    // 2026-05-15 portfolio extension of Bug J: report whether the
    // pre-refresh cache was stale by *file mtime* (the operator-
    // meaningful datum) — surfaced as a diagnostic only. The refresh
    // proceeds regardless because the whole point of refresh-trust is
    // to recover from a stale cache.
    if cache_path.exists() {
        if let Ok(Some(parsed)) = TrustedRoot::load_cached(&cache_path) {
            let pre_refresh_stale = parsed
                .is_stale(
                    Utc::now(),
                    TrustRootStalenessAnchor::cache_file_mtime(&cache_path),
                )
                .unwrap_or(false);
            if pre_refresh_stale {
                eprintln!(
                    "audit refresh-trust: invariant={}",
                    cortex_ledger::TRUSTED_ROOT_CACHE_STALE_INVARIANT
                );
                eprintln!(
                    "audit refresh-trust: pre-refresh cache `{}` is stale by mtime; refreshing",
                    cache_path.display()
                );
            }
        }
    }

    let body = match fetch_trusted_root_bytes(&url) {
        Ok(bytes) => bytes,
        Err(err) => {
            eprintln!("audit refresh-trust: failed to fetch trusted_root.json from {url}: {err}");
            report.outcome = REFRESH_TRUST_OUTCOME_HTTP_ERROR;
            report.failure_reason = Some(format!("{err}"));
            return Exit::PreconditionUnmet;
        }
    };

    let parsed = match TrustedRoot::parse_bytes(&body) {
        Ok(root) => root,
        Err(err) => {
            eprintln!("audit refresh-trust: fetched payload from {url} did not parse: {err}");
            report.outcome = REFRESH_TRUST_OUTCOME_PARSE_ERROR;
            report.failure_reason = Some(format!("{err}"));
            return Exit::PreconditionUnmet;
        }
    };
    let new_signed_at = parsed.metadata_signed_at();
    report.new_signed_at = new_signed_at;

    // Chain-of-trust check (structural): the new root's mediaType,
    // non-empty tlogs, and validity windows are already validated by
    // `parse_bytes`. The cryptographic signature check against the
    // embedded TUF root is the deferred slice; today we surface
    // `signature_invalid` only if the fetched payload regresses below
    // the embedded snapshot's freshness floor. This is intentionally
    // conservative: if the mirror is serving a root older than the
    // embedded snapshot the operator likely hit a stale mirror or a
    // downgrade attack, and the refresh should not silently install it.
    if let (Some(new), Some(embedded)) = (
        new_signed_at,
        TrustedRoot::embedded()
            .ok()
            .and_then(|r| r.metadata_signed_at()),
    ) {
        if new < embedded {
            eprintln!(
                "audit refresh-trust: fetched trusted_root.json from {url} is older ({new}) than embedded snapshot ({embedded}); refusing to install"
            );
            report.outcome = REFRESH_TRUST_OUTCOME_SIGNATURE_INVALID;
            report.failure_reason = Some(format!(
                "fetched activation {new} predates embedded snapshot {embedded}"
            ));
            return Exit::PreconditionUnmet;
        }
    }

    // Stale-to-stale detection: previously-cached root was stale AND
    // the fetched root is no newer than the previous cache. Operators
    // see this when their TUF mirror has not refreshed and the
    // refresh is a no-op.
    if let (Some(prev), Some(new)) = (previous_signed_at, new_signed_at) {
        if new <= prev {
            eprintln!(
                "audit refresh-trust: fetched root from {url} is not newer than the cached root ({new} <= {prev}); cache not rewritten"
            );
            report.outcome = REFRESH_TRUST_OUTCOME_STALE_TO_STALE;
            report.cache_written = false;
            return Exit::Ok;
        }
    }

    if let Err(err) = parsed.write_atomic(&cache_path) {
        eprintln!(
            "audit refresh-trust: failed to write trusted_root.json cache `{}`: {err}",
            cache_path.display()
        );
        report.outcome = REFRESH_TRUST_OUTCOME_HTTP_ERROR;
        report.failure_reason = Some(format!("{err}"));
        return Exit::Internal;
    }
    report.cache_written = true;
    report.outcome = REFRESH_TRUST_OUTCOME_OK;
    if !output::json_enabled() {
        match (previous_signed_at, new_signed_at) {
            (Some(prev), Some(new)) => println!(
                "audit refresh-trust: refreshed trusted_root.json (previous={prev}, new={new}) -> {}",
                cache_path.display()
            ),
            (None, Some(new)) => println!(
                "audit refresh-trust: installed trusted_root.json (new={new}) -> {}",
                cache_path.display()
            ),
            _ => println!(
                "audit refresh-trust: installed trusted_root.json -> {}",
                cache_path.display()
            ),
        }
    }
    Exit::Ok
}

/// Errors produced by the trust-root fetch helper.
#[derive(Debug)]
enum FetchError {
    /// The supplied URL did not use a scheme we know how to fetch.
    UnsupportedScheme { url: String },
    /// The local `curl` invocation could not be spawned.
    Spawn { source: std::io::Error },
    /// `curl` exited non-zero (network error, 4xx/5xx, timeout).
    CurlNonZero { status: String, stderr: String },
    /// `file://` fetch could not read the local path.
    FileRead {
        path: String,
        source: std::io::Error,
    },
}

impl std::fmt::Display for FetchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnsupportedScheme { url } => write!(
                f,
                "unsupported URL scheme for `{url}` (expected http, https, or file)"
            ),
            Self::Spawn { source } => write!(f, "failed to spawn curl: {source}"),
            Self::CurlNonZero { status, stderr } => {
                write!(f, "curl exited with status {status}: {stderr}")
            }
            Self::FileRead { path, source } => {
                write!(f, "failed to read file `{path}`: {source}")
            }
        }
    }
}

impl std::error::Error for FetchError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Spawn { source } | Self::FileRead { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// Fetch the body of a `trusted_root.json` URL.
///
/// Supported schemes:
/// - `https://` / `http://` via the host `curl` binary. cargo-vet readiness
///   is in SKIP today, so the doctrine guardrail says we cannot pull a new
///   HTTP-client crate. `curl` is part of the documented CI/local-green
///   prerequisite set already, and the call site here uses it with the
///   fail-fast flags `-sSfL --max-time` so a non-2xx response surfaces as
///   a non-zero exit rather than as the response body.
/// - `file://` via [`std::fs::read`]. The file-scheme path is the test and
///   air-gapped operator path: stage a `trusted_root.json` out-of-band,
///   then refresh against `file:///path/to/file.json` to install it
///   atomically.
fn fetch_trusted_root_bytes(url: &str) -> Result<Vec<u8>, FetchError> {
    if let Some(rest) = url.strip_prefix("file://") {
        // Windows file URLs use either `file:///C:/...` or `file://C:/...`.
        // Both reduce to the platform path after stripping the leading
        // slash count cargo's URL parser would expect.
        let trimmed = rest.trim_start_matches('/');
        let path: PathBuf = if cfg!(windows) {
            PathBuf::from(trimmed.replace('/', "\\"))
        } else {
            PathBuf::from(format!("/{trimmed}"))
        };
        return std::fs::read(&path).map_err(|source| FetchError::FileRead {
            path: path.display().to_string(),
            source,
        });
    }
    if !(url.starts_with("https://") || url.starts_with("http://")) {
        return Err(FetchError::UnsupportedScheme {
            url: url.to_string(),
        });
    }
    let output = std::process::Command::new("curl")
        .args(["-sSfL", "--max-time", "30", "--", url])
        .output()
        .map_err(|source| FetchError::Spawn { source })?;
    if !output.status.success() {
        return Err(FetchError::CurlNonZero {
            status: output
                .status
                .code()
                .map(|c| c.to_string())
                .unwrap_or_else(|| "signal".to_string()),
            stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
        });
    }
    Ok(output.stdout)
}

/// Decide which "structural" exit applies when the audit could not even
/// open / iterate the file. `Decode` is the canonical "byte-flip in the
/// middle of a row" case — that's `ChainCorruption`. `Io` is a missing
/// directory, unreadable path, or other OS-level precondition failure —
/// `PreconditionUnmet` (7) rather than `Internal` (64), because the
/// operator can act on it directly (BUG-2 fix). Encode bugs stay `Internal`.
fn map_open_err(e: &JsonlError) -> Exit {
    match e {
        JsonlError::Decode { .. } | JsonlError::ChainBroken(_) => Exit::ChainCorruption,
        JsonlError::Validation(_) => Exit::PreconditionUnmet,
        JsonlError::Io { .. } => Exit::PreconditionUnmet,
        JsonlError::Encode(_) => Exit::Internal,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;
    use cortex_core::{
        Event, EventId, EventSource, EventType, PolicyDecision, ProofState, SCHEMA_VERSION,
    };
    use cortex_ledger::{append_policy_decision_test_allow, JsonlLog};
    use std::io::Write;
    use tempfile::tempdir;

    fn allow_policy() -> PolicyDecision {
        append_policy_decision_test_allow()
    }

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

    #[test]
    fn clean_chain_returns_ok() {
        let tmp = tempdir().unwrap();
        let log_path = tmp.path().join("events.jsonl");
        let mut log = JsonlLog::open(&log_path).unwrap();
        for i in 0..3u64 {
            log.append(fixture_event(i), &allow_policy()).unwrap();
        }
        let exit = run_verify(VerifyArgs {
            event_log: Some(log_path),
            db: Some(tmp.path().join("cortex.db")),
            signed: false,
            verification_key: None,
            attestation: None,
            require_v1_to_v2_boundary: false,
            against: None,
            against_history: None,
            against_external: None,
            witness_key_registry: None,
        });
        assert_eq!(exit, Exit::Ok);
    }

    /// Lane 1.C T-1.C.3 acceptance: byte-wise corruption (a malformed JSON
    /// line in the middle of the file) MUST surface as `ChainCorruption`.
    #[test]
    fn bytewise_corruption_returns_chain_corruption() {
        let tmp = tempdir().unwrap();
        let log_path = tmp.path().join("events.jsonl");
        let mut log = JsonlLog::open(&log_path).unwrap();
        log.append(fixture_event(0), &allow_policy()).unwrap();
        // Append junk line bypassing the API to simulate disk-level damage.
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(&log_path)
            .unwrap();
        writeln!(f, "{{not valid json").unwrap();
        f.sync_all().unwrap();
        drop(f);

        let exit = run_verify(VerifyArgs {
            event_log: Some(log_path),
            db: Some(tmp.path().join("cortex.db")),
            signed: false,
            verification_key: None,
            attestation: None,
            require_v1_to_v2_boundary: false,
            against: None,
            against_history: None,
            against_external: None,
            witness_key_registry: None,
        });
        assert_eq!(exit, Exit::ChainCorruption);
    }

    /// Lane 1.C T-1.C.3 acceptance: an "ordinal gap" — represented in the
    /// JSONL log as an Orphan (`prev_event_hash` does not point at the
    /// previous row's `event_hash`) — MUST surface as `IntegrityFailure`.
    #[test]
    fn ordinal_gap_returns_integrity_failure() {
        let tmp = tempdir().unwrap();
        let log_path = tmp.path().join("events.jsonl");
        let mut log = JsonlLog::open(&log_path).unwrap();
        for i in 0..3u64 {
            log.append(fixture_event(i), &allow_policy()).unwrap();
        }
        // Tamper row 2's prev_event_hash and re-seal it so the row
        // is internally consistent (no hash break) but orphaned.
        let raw = std::fs::read_to_string(&log_path).unwrap();
        let mut rows: Vec<Event> = raw
            .lines()
            .filter(|l| !l.trim().is_empty())
            .map(|l| serde_json::from_str::<Event>(l).unwrap())
            .collect();
        rows[1].prev_event_hash = Some("0".repeat(64));
        cortex_ledger::seal(&mut rows[1]);

        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .create(true)
            .open(&log_path)
            .unwrap();
        for r in &rows {
            writeln!(f, "{}", serde_json::to_string(r).unwrap()).unwrap();
        }
        f.sync_all().unwrap();
        drop(f);

        let exit = run_verify(VerifyArgs {
            event_log: Some(log_path),
            db: Some(tmp.path().join("cortex.db")),
            signed: false,
            verification_key: None,
            attestation: None,
            require_v1_to_v2_boundary: false,
            against: None,
            against_history: None,
            against_external: None,
            witness_key_registry: None,
        });
        assert_eq!(exit, Exit::IntegrityFailure);
    }

    // =========================================================================
    // Commit A — `cortex audit verify` proof-closure fold (ADR 0036)
    //
    // These tests pin the contract that the three per-axis contributors
    // (`hash_chain_closure`, `signed_chain_closure`, `v1_to_v2_boundary`)
    // compose into a single typed `ProofClosureReport`, that any hash-chain
    // Reject collapses the whole report to `Broken`, and that the weakest
    // truthful state survives otherwise. The stable invariant key for the
    // fold is `VERIFY_PROOF_CLOSURE_COMPOSED_REPORT_INVARIANT`.
    // =========================================================================

    fn allow_contribution(rule_id: &'static str) -> PolicyContribution {
        PolicyContribution::new(rule_id, PolicyOutcome::Allow, "ok").expect("static contribution")
    }

    fn reject_contribution(rule_id: &'static str) -> PolicyContribution {
        PolicyContribution::new(rule_id, PolicyOutcome::Reject, "broken")
            .expect("static contribution")
    }

    fn quarantine_contribution(rule_id: &'static str) -> PolicyContribution {
        PolicyContribution::new(rule_id, PolicyOutcome::Quarantine, "partial")
            .expect("static contribution")
    }

    #[test]
    fn verify_proof_closure_fold_composes_three_axes_into_one_report() {
        let report = compose_verify_proof_closure_report(&[
            allow_contribution(VERIFY_HASH_CHAIN_CLOSURE_RULE_ID),
            allow_contribution(VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID),
            allow_contribution(VERIFY_V1_TO_V2_BOUNDARY_RULE_ID),
        ]);
        assert_eq!(report.state(), ProofState::FullChainVerified);
        assert_eq!(report.verified_edges().len(), 3);
        assert!(report.failing_edges().is_empty());
    }

    #[test]
    fn verify_proof_closure_fold_rejects_when_hash_chain_contributor_rejects() {
        let report = compose_verify_proof_closure_report(&[
            reject_contribution(VERIFY_HASH_CHAIN_CLOSURE_RULE_ID),
            allow_contribution(VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID),
            allow_contribution(VERIFY_V1_TO_V2_BOUNDARY_RULE_ID),
        ]);
        assert_eq!(report.state(), ProofState::Broken);
        assert!(report.is_broken());
        assert!(report.failing_edges().iter().any(|edge| matches!(
            edge.kind,
            ProofEdgeKind::HashChain
        ) && matches!(
            edge.failure,
            ProofEdgeFailure::Mismatch
        )));
    }

    #[test]
    fn verify_proof_closure_fold_rejects_when_any_single_contributor_rejects() {
        // Per audit composition rule: hash-chain Reject is the strongest case,
        // but any contributor Reject collapses the report through the broken
        // failing-edge classification.
        for reject_rule in [
            VERIFY_HASH_CHAIN_CLOSURE_RULE_ID,
            VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID,
            VERIFY_V1_TO_V2_BOUNDARY_RULE_ID,
        ] {
            let contributions: Vec<PolicyContribution> = [
                VERIFY_HASH_CHAIN_CLOSURE_RULE_ID,
                VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID,
                VERIFY_V1_TO_V2_BOUNDARY_RULE_ID,
            ]
            .into_iter()
            .map(|rule| {
                if rule == reject_rule {
                    reject_contribution(rule)
                } else {
                    allow_contribution(rule)
                }
            })
            .collect();
            let report = compose_verify_proof_closure_report(&contributions);
            assert_eq!(
                report.state(),
                ProofState::Broken,
                "rejecting {reject_rule} must collapse fold to Broken"
            );
        }
    }

    #[test]
    fn verify_proof_closure_fold_downgrades_to_partial_on_quarantine() {
        let report = compose_verify_proof_closure_report(&[
            allow_contribution(VERIFY_HASH_CHAIN_CLOSURE_RULE_ID),
            allow_contribution(VERIFY_SIGNED_CHAIN_CLOSURE_RULE_ID),
            quarantine_contribution(VERIFY_V1_TO_V2_BOUNDARY_RULE_ID),
        ]);
        assert_eq!(report.state(), ProofState::Partial);
        assert!(!report.is_broken());
        assert!(!report.is_full_chain_verified());
    }

    #[test]
    fn verify_proof_closure_invariant_key_is_stable() {
        // Pin the stable invariant string: a downstream consumer or schema
        // contract reads this key off the audit verify envelope, so the
        // exact text is load-bearing.
        assert_eq!(
            VERIFY_PROOF_CLOSURE_COMPOSED_REPORT_INVARIANT,
            "audit.verify.proof_closure.composed_report"
        );
    }
}